A Simple C# Sorted Observable Collection

I know that this can be done with ICollectionView without modifying the underlying order, but for times when I really must have my bound collection sorted, I use this:

    /// <summary>
    /// A Sorted ObservableCollection.
    /// - Sorts on Insert.
    /// - Requires that T implements IComparable.
    /// </summary>
    /// <typeparam name="T">The type held within collection</typeparam>
    public class SortedObservableCollection<T> : ObservableCollection<T>
        where T : IComparable
    {
        protected override void InsertItem(int index, T item)
        {
            for (var i = 0; i < Count; i++)
            {
                switch (Math.Sign(this[i].CompareTo(item)))
                {
                    case 0:
                    case 1:
                        base.InsertItem(i, item);
                        return;
                    case -1:
                        break;

                }
            }
            base.InsertItem(Count, item);
        }
    }

It sorts on insert and is O(n) so be careful with large collections.

Tagged , , , , , , , , , , ,

2 thoughts on “A Simple C# Sorted Observable Collection

  1. Torsten says:

    Hi Richard,

    I faced the same challange and implemented a sorted observable collection somewhat more complex (and hopefully more complete and performant):

    http://www.dotmaniac.net/simple-sorted-observablecollection/

    Thanks for your post!

Leave a Reply

%d bloggers like this: