对ObservableCollection< string>进行排序通过C# [英] Sort ObservableCollection<string> through C#
问题描述
我在ObservableCollection<string>
以下.我需要按字母顺序排序.
I have below ObservableCollection<string>
. I need to sort this alphabetically.
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
.但是我不知道如何正确使用它.
I tried _animals.OrderByDescending
. But I don't know how to use it correctly.
_animals.OrderByDescending(a => a.<what_is_here_?>);
我该怎么做?
推荐答案
简介
基本上,如果需要显示排序的集合,请考虑使用CollectionViewSource
类:将其Source
属性分配(绑定")到源集合— ObservableCollection<T>
类的实例.
Introduction
Basically, if there is a need to display a sorted collection, please consider using the CollectionViewSource
class: assign ("bind") its Source
property to the source collection — an instance of the ObservableCollection<T>
class.
这个想法是 CollectionViewSource
类提供了CollectionView
类的一个实例.这是原始(源)集合的投影",但是具有应用的排序,过滤等功能.
The idea is that CollectionViewSource
class provides an instance of the CollectionView
class. This is kind of "projection" of the original (source) collection, but with applied sorting, filtering, etc.
参考文献:
- How to: Sort and Group Data Using a View in XAML.
- WPF’s CollectionViewSource.
WPF 4.5为CollectionViewSource
引入了实时塑形"功能.
WPF 4.5 introduces "Live Shaping" feature for CollectionViewSource
.
参考文献:
- WPF 4.5 New Feature: Live Shaping.
- CollectionViewSource.IsLiveSorting Property.
- Repositioning data as the data's values change (Live shaping).
如果仍然需要对ObservableCollection<T>
类的实例进行排序,可以按照以下步骤进行.
ObservableCollection<T>
类本身没有排序方法.但是,可以重新创建集合以对项目进行排序:
If there still a need to sort an instance of the ObservableCollection<T>
class, here is how it can be done.
The ObservableCollection<T>
class itself does not have sort method. But, the collection could be re-created to have items sorted:
// 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>
接口的类的新实例).因此,有必要重新创建集合.
Additional details
Please note that OrderBy()
and OrderByDescending()
methods (as other LINQ–extension methods) do not modify the source collection! They instead create a new sequence (i.e. a new instance of the class that implements IEnumerable<T>
interface). Thus, it is necessary to re-create the collection.
这篇关于对ObservableCollection< string>进行排序通过C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!