score:2

Accepted answer

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

score:0

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.

score:0

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

score:1

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.

score:0

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.


Related Articles