How do I sort an observable collection? How do I sort an observable collection? wpf wpf

How do I sort an observable collection?


This simple extension worked beautifully for me. I just had to make sure that MyObject was IComparable. When the sort method is called on the observable collection of MyObjects, the CompareTo method on MyObject is called, which calls my Logical Sort method. While it doesn't have all the bells and whistles of the rest of the answers posted here, it's exactly what I needed.

static class Extensions{    public static void Sort<T>(this ObservableCollection<T> collection) where T : IComparable    {        List<T> sorted = collection.OrderBy(x => x).ToList();        for (int i = 0; i < sorted.Count(); i++)            collection.Move(collection.IndexOf(sorted[i]), i);    }}public class MyObject: IComparable{    public int CompareTo(object o)    {        MyObject a = this;        MyObject b = (MyObject)o;        return Utils.LogicalStringCompare(a.Title, b.Title);    }    public string Title;}  .  .  .myCollection = new ObservableCollection<MyObject>();//add stuff to collectionmyCollection.Sort();


I found a relevant blog entry that provides a better answer than the ones here:

http://kiwigis.blogspot.com/2010/03/how-to-sort-obversablecollection.html

UPDATE

The ObservableSortedList that @romkyns points out in the comments automatically maintains sort order.

Implements an observable collection which maintains its items in sorted order. In particular, changes to item properties that result in order changes are handled correctly.

However note also the remark

May be buggy due to the comparative complexity of the interface involved and its relatively poor documentation (see https://stackoverflow.com/a/5883947/33080).


You can use this simple method:

public static void Sort<TSource, TKey>(this Collection<TSource> source, Func<TSource, TKey> keySelector){    List<TSource> sortedList = source.OrderBy(keySelector).ToList();    source.Clear();    foreach (var sortedItem in sortedList)        source.Add(sortedItem);}

You can sort like this:

_collection.Sort(i => i.Key);