对 ObservableCollection<T> 进行排序

WAQ*_*WAQ 2 sorting wpf treeview listview observablecollection

我有两个独立的可观察集合,其中 T 是用户定义的类。这些集合绑定到列表视图和树视图。我想按排序顺序显示集合中的项目。我似乎在列表和树视图上没有找到任何排序功能。集合中的元素可以在运行时删除/添加。实现这一目标的最佳方法是什么?

提前致谢。干杯!

She*_*dan 5

Move您可以通过扩展类使用内部方法非常轻松地自己实现此行为ObservableCollection<T>。这是一个简化的示例:

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];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

感谢@ThomasLevesque 提供了Sort上面所示的更有效的方法

然后你可以像这样使用它:

YourCollection.Sort(c => c.PropertyToSortBy);
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案“非常”低效...其复杂度至少为 O(n²)。大多数排序算法的复杂度为 O(n log n)。 (2认同)