Sorting ObservableCollection<T>

邮差的信 提交于 2019-12-19 10:32:17

问题


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!


回答1:


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);



回答2:


  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.



来源:https://stackoverflow.com/questions/19363710/sorting-observablecollectiont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!