ObservableCollection对键进行排序扩展方法

时间:2014-08-18 13:35:02

标签: c# sorting extension-methods observablecollection

嗨我有一个ObservableCollection我在哪里添加一个项目,我想对它进行排序。

我想在密钥上对其进行排序,例如:

collection.OrderByDescending(x => x.property)

我已经创建了一个扩展方法,它将在添加项目时进行排序(.Add),但是,扩展方法需要执行类似上面的代码。使用下面的扩展方法中的代码,有人可以帮助我吗?

public static void Sort<T>(this ObservableCollection<T> collection) where T : IComparable
{
   List<T> sorted = collection.OrderByDescending(x => x).ToList();
   for (int i = 0; i < sorted.Count(); i++)
        collection.Move(collection.IndexOf(sorted[i]), i);
}

通用真的需要实现IComparable接口吗? (我对扩展方法很新。)

2 个答案:

答案 0 :(得分:1)

通常情况下,当您使用ObservableCollection<T>时,不要直接对其进行排序;相反,您对集合的视图应用排序(ICollectionView interface)。如果您将UI直接绑定到ObservableCollection<T>,则可以应用如下排序:

var view = CollectionViewSource.GetDefaultView(collection);
view.SortDescriptions.Add(new SortDescription("MyProperty", ListSortDirection.Descending));

你只需要做一次;如果添加或删除项目,集合视图将自动重新排序。如果您更改MyProperty的值,它也会有效,只要T实现INotifyPropertyChanged

另请参阅:How to: Get the Default View of a Data Collection

(我假设您正在编写WPF应用程序;这种方法不适用于Windows Phone或Windows应用商店应用程序)

答案 1 :(得分:1)

这对我有用:

ConceptItems = new ObservableCollection<DataConcept>(ConceptItems.OrderBy(i => i.DateColumn));
相关问题