Dutton

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.


Share this: