对ObservableCollection< T>进行排序 [英] Sorting ObservableCollection<T>
问题描述
我有两个单独的可观察集合,其中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?
先谢谢了.干杯!
推荐答案
通过扩展ObservableCollection<T>
类,您可以使用内部Move
方法非常轻松地实现此行为.这是一个简化的示例:
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];
}
}
}
感谢@ThomasLevesque获得上面显示的更有效的
Sort
方法
然后您可以像这样使用它:
You can then use it like this:
YourCollection.Sort(c => c.PropertyToSortBy);
这篇关于对ObservableCollection< T>进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!