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);
                    case -1:

            base.InsertItem(Count, item);

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

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

4 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):


    Thanks for your post!

  2. Tony G says:

    You’ve made a design choice here that you want to allow duplicate items. That might not be the same choice that others would make, depending on the application. Just sayin..
    I also notice that this code is exactly the same as that from another blog, minus the one line which prevents duplicate items. I know you didn’t say you wrote this, just that you use it. But attribution to the source is usually appropriate. Just sayin…

    • richard says:

      Hi Tony, yes that was a design decision for my particular use case to allow dupes. Have never seen that other link before so I’m afraid the similarity is a coincidence.

Leave a Reply

%d bloggers like this: