开发者

How do I sort observable collection?

I know there are other posts similar to this 开发者_C百科one, but none of them answered my question fully.

I have multiple different observable collections in a WPF application that I am working on, and I need to just do a simple alphabetical sort on them to have them display in alphabetical order.

Is there an easy way to do this with Linq? If not, is there another easy way I can do this?


You can provide your own custom sorting logic or can use CollectionView sort descriptors property to sort your collection. For start look at these links, they might help - http://bea.stollnitz.com/blog/?p=17 http://www.wpftutorial.net/DataViews.html http://bea.stollnitz.com/blog/?p=24


What comes to mind:

  1. Sort in View, not in ViewModel
  2. Pull out into a list, sort list, clear collection, insert back
  3. Custom SortedObservableCollection, but I am not sure how would View react to this.

Not sure about your specific needs.


You can use sorted observable collection - it is a collection which maintains the items in the sorted order at all times (so you just insert the item and it will get inserted into correct place into the collection).

There are several implementations out there - like this one or this one.


You should use CollectionViewSource instead of ObservableCollection or you can wrap your collection in CollectionViewSource.

public CollectionViewSource GetSortedView{
   get{
      CollectionViewSource view = new CollectionViewSource(myColl);
      view.SortDescriptors.Add(new SortDescriptor("propertyname"), Ascending);
      return view;
   }
}

Benefit is, if you bind this view to datagrid etc, it will show the column sort sign and also let the user do further sorting.


Have a look at this one http://mokosh.co.uk/post/2009/08/04/how-to-sort-observablecollection/

Looks to be a clean and easy implementation.

And if you need to use just linq, you can use OrderBy extension method. More info on orderby method is here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜