Ordering a C# ObservableCollection

Published on

As I've been playing around a lot in Avalonia and MVVM recently, I encountered a requirement of storing a reactive collection of ordered items and this is how I achieved it.

The implementation

This simple implementation wraps the existing ObservableCollection<T> from System.Collections.ObjectModel and holds properties for the property selector for sorting, as well as whether the sort should be descending.

public class SortedObservableCollection<T> : ObservableCollection<T>
{
    public SortedObservableCollection(IEnumerable<T> collection) : base(collection)
    {
    }
    
    public Func<T, object>? SortingSelector { get; init; }
    public bool Descending { get; init; }
    
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        base.OnCollectionChanged(e);
        if (SortingSelector is null
            || e.Action == NotifyCollectionChangedAction.Remove
            || e.Action == NotifyCollectionChangedAction.Reset)
        {
            return;
        }
                      
        var query = this
            .Select((item, index) => (Item: item, Index: index));
        query = Descending
            ? query.OrderByDescending(tuple => SortingSelector(tuple.Item))
            : query.OrderBy(tuple => SortingSelector(tuple.Item));

        var map = query.Select((tuple, index) => (OldIndex:tuple.Index, NewIndex:index))
            .Where(o => o.OldIndex != o.NewIndex);

        using var enumerator = map.GetEnumerator();
        if (enumerator.MoveNext())
        {
            Move(enumerator.Current.OldIndex, enumerator.Current.NewIndex);
        }
    }
}

When the collection has changed, we ignore Remove and Reset NotifyCollectionChangedAction events as these will either not affect order, or their operations have already caused a re-ordering.

We then perform the sort and perform a Move() for each item that has changed index.

Using this method means events will fire for the remove and add internally, but for my simple use-cases this is not an issue but perhaps something I could take a look at again in the future.

Summary

This post I shared a simple way of implementing an ordered observable collection in C# for my own future reference for re-use/to come back and improve.

Feel free to use this in your own projects according to your requirements.