1

I have a ObserverableCollection in my WPF application and I would like to sort it according to a property. Consider:

var MyCollection = new ObserverableCollection<MyViewModel>;

where MyViewModel have a property SortOrder that returns an integer that represent its position in the collection. The integer will not necessary start with 1 or increment by 1 for each object.

I can physical move the objects around on a wpf Canvas (like folders and icons on the desktop) and the SortOrder depends on the position. So when I move an object I need to update its position in the collection.

I also need to add objects to the collection, so how can I do that while ensuring that the objects are ordered according to SortOrder?

The collection will typically contain between 1-30 items.

Kim Larsen
  • 13
  • 6
  • Have you seen [this](http://stackoverflow.com/questions/1945461/how-do-i-sort-an-observable-collection)? – Pikoh Apr 12 '16 at 09:32
  • Take a look at [Binding to Collections / Collection Views](https://msdn.microsoft.com/en-us/library/ms752347(v=vs.100).aspx#binding_to_collections) – Clemens Apr 12 '16 at 09:43

1 Answers1

0

With inspiration from, this you can create an extension like:

public static class Extensions
{
    public static void Sort<TSource, TKey>(this ObservableCollection<TSource> collection, Func<TSource, TKey> keySelector)
    {
        List<TSource> sorted = collection.OrderBy(keySelector).ToList();
        for (int i = 0; i < sorted.Count(); i++)
            collection.Move(collection.IndexOf(sorted[i]), i);
    }
    public static void AddSort(this ObservableCollection<MyViewModel> collection, MyViewModel newItem)
    {
        var index = collection.Where(x => x.SortOrder) < newItem.SortOrder)).Count();
        collection.Insert(index, newItem);
    }
}
Community
  • 1
  • 1
Daltons
  • 2,671
  • 2
  • 18
  • 24