我在下面ObservableCollection<string>。我需要 进行排序 按字母顺序这一点。
ObservableCollection<string>
private ObservableCollection<string> _animals = new ObservableCollection<string> { "Cat", "Dog", "Bear", "Lion", "Mouse", "Horse", "Rat", "Elephant", "Kangaroo", "Lizard", "Snake", "Frog", "Fish", "Butterfly", "Human", "Cow", "Bumble Bee" };
我试过了_animals.OrderByDescending。但是我不知道如何正确使用它。
_animals.OrderByDescending
_animals.OrderByDescending(a => a.<what_is_here_?>);
我怎样才能做到这一点?
基本上,如果需要显示排序的集合,请考虑使用CollectionViewSource该类:将其Source属性分配(“绑定”)给源集合— ObservableCollection<T>该类的实例。
CollectionViewSource
Source
ObservableCollection<T>
这个想法是,CollectionViewSource类提供的实例CollectionView类。这是原始(源)集合的“投影”,但是具有应用的排序,过滤等功能。
CollectionView
参考文献:
WPF 4.5引入了“实时成形”功能CollectionViewSource。
如果仍然需要对类的实例进行排序ObservableCollection<T>,请按照以下步骤进行。在ObservableCollection<T>类本身不具有排序方法。但是,可以重新创建集合以对项目进行排序:
// Animals property setter must raise "property changed" event to notify binding clients. // See INotifyPropertyChanged interface for details. Animals = new ObservableCollection<string> { "Cat", "Dog", "Bear", "Lion", "Mouse", "Horse", "Rat", "Elephant", "Kangaroo", "Lizard", "Snake", "Frog", "Fish", "Butterfly", "Human", "Cow", "Bumble Bee" }; ... Animals = new ObservableCollection<string>(Animals.OrderBy(i => i));
请注意,OrderBy()和OrderByDescending()方法(与其他LINQ扩展方法一样) 不会修改 源集合!相反,它们 创建一个新序列 (即,实现IEnumerable<T>接口的类的新实例)。因此,有必要重新创建集合。
OrderBy()
OrderByDescending()
IEnumerable<T>