排序 ObservableCollection<string>通过 C# [英] Sort ObservableCollection&lt;string&gt; through C#

查看:25
本文介绍了排序 ObservableCollection<string>通过 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 ObservableCollection.我需要按字母顺序排序.

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 类的一个实例.

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.

参考文献:

WPF 4.5 引入了实时整形";CollectionViewSource 的功能.

WPF 4.5 introduces "Live Shaping" feature for CollectionViewSource.

参考文献:

如果仍然需要对 ObservableCollection<T> 类的实例进行排序,这里是如何完成的.ObservableCollection 类本身没有 sort 方法.但是,可以重新创建集合以对项目进行排序:

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 接口的类的新实例).因此,有必要重新创建集合.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆