WAQ
WAQ

Reputation: 2616

Sorting ObservableCollection<T>

I have Two separate observable Collection where T is a user defined class. These collections are binded to List View and Tree View. I want to show the items of the collections in sorted order. I don't seem to find any sort function on the List and Tree view. Elements in Collections can be removed/added on run time. What is the best way to achieve this?

Thanks in advance. Cheers!

Upvotes: 2

Views: 4229

Answers (2)

Neil
Neil

Reputation: 1

  private void ApplySort(IEnumerable<T> sortedItems)
  {
     var sortedItemsList = sortedItems.ToList();
     for (int i = 0; i < sortedItemsList.Count; i++)
     {
        if((object)(this[i]) != (object)(sortedItemsList[i]))
           this[i] = sortedItemsList[i];
     }
  }

Can reduce the number of CollectionChanged events for better performance.

Upvotes: 0

Sheridan
Sheridan

Reputation: 69959

You can implement this behaviour yourself quite easily using the internal Move method by extending the ObservableCollection<T> class. Here is a simplified example:

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

    public SortableObservableCollection() : base() { }

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

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

    public void SortDescending<TKey>(Func<T, TKey> keySelector)
    {
        Sort(Items.OrderByDescending(keySelector));
    }

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

    public void Sort(IEnumerable<T> sortedItems)
    {
        List<T> sortedItemsList = sortedItems.ToList();
        for (int i = 0; i < sortedItemsList.Count; i++)
        {
            Items[i] = sortedItemsList[i];
        }
    }
}

Thanks to @ThomasLevesque for the more efficient Sort method shown above

You can then use it like this:

YourCollection.Sort(c => c.PropertyToSortBy);

Upvotes: 5

Related Questions