You probably have had the need to sort an ObservableCollection at some point in one of your applications by either ascending or descending order.  Of course, you can always use the ObservableCollection.OrderBy and ObservableCollection.OrderByDescending, but these methods just return a new collection of IOrderedEnumerable, which forces you have to rebind the DataContext/ItemsSource in your UI, which could be a pain.  So instead, wouldn’t it be nice to have an ObservableCollection that you could call a Sort method on, give it a lambda to sort on and a direction, then have it perform the sort without having to rebind to the UI.  Well, it is not a difficult as you may think.  So lets go ahead and write one.

public class SortableObservableCollection<T> : ObservableCollection<T>
{
  public SortableObservableCollection(List<T> list)
     : base(list)
  {
  }

  public SortableObservableCollection(IEnumerable<T> collection)
     : base(collection)
  {
  }

  public void Sort<TKey>(Func<T, TKey> keySelector, System.ComponentModel.ListSortDirection direction)
  {
     switch (direction)
     {
        case System.ComponentModel.ListSortDirection.Ascending:
           {
              ApplySort(Items.OrderBy(keySelector));
              break;
           }
        case System.ComponentModel.ListSortDirection.Descending:
           {
              ApplySort(Items.OrderByDescending(keySelector));
              break;
           }
     }
  }

  public void Sort<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer)
  {
     ApplySort(Items.OrderBy(keySelector, comparer));
  }

  private void ApplySort(IEnumerable<T> sortedItems)
  {
     var sortedItemsList = sortedItems.ToList();

     foreach (var item in sortedItemsList)
     {
        Move(IndexOf(item), sortedItemsList.IndexOf(item));
     }
  }
}

Now we can create a new SortableObservableCollection<T> and sort it either direction without having to return a new IOrderedEnumerable and rebind the DataContext/ItemsSource.

//sort ascending
MySortableList.Sort(x => x.Name, ListSortDirection.Ascending);

//sort descending
MySortableList.Sort(x => x.Name, ListSortDirection.Descending);

When you sort your collection, the UI is notified that something has changed and updates itself automatically.

Brian Lagunas

View all posts

Follow Me

Follow me on Twitter, subscribe to my YouTube channel, and watch me stream live on Twitch.