Introducing SortingObservableCollection

ObservableCollections are awesome. The two way binding lets your user seamlessly update your model and any programmatic changes to the model will be seamlessly reflected in the view.

I wanted one that kept it’s items in order, no matter what. It should maintain order as items are added and watch them via INotifyPropertyChanged to move them automatically. So here it is on CodePlex and NuGet. Sample usage is:

var collection = new SortingObservableCollection<MyViewModel, int>(Comparer<int>.Default, model => model.IntPropertyToSortOn);

collection.Add(new MyViewModel(3));
collection.Add(new MyViewModel(1));
collection.Add(new MyViewModel(2));

// At this point, the order is 1, 2, 3

collection[0].IntPropertyToSortOn = 4;
// As long as IntPropertyToSortOn uses INotifyPropertyChanged, this will cause the collection to resort correctly