对ObservableCollection进行排序-最佳方法是什么? [英] Sort ObservableCollection - what is the best approach?

查看:485
本文介绍了对ObservableCollection进行排序-最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ObservableCollection,其中MyData是具有4个属性的类,即int id,字符串名称,bool IsSelected,字符串IsVisible.

I have a ObservableCollection , where MyData is a class with 4 properties i.e. int id, string name, bool IsSelected, string IsVisible.

此ObservableCollection绑定到带有复选框的组合框(例如,城市数据).现在,当用户选中复选框时,下一次打开下拉菜单时,所有选择都应按名称升序排列在顶部.

This ObservableCollection is binded to a combobox with checkboxes(Cities data for example). Now, when the user checks the checkboxes then next time when he opens the drop down - all selections should come on top in ascending order by name.

当用户在组合框中键入3个字符时,我还实现了自动完成功能,下拉菜单将首先显示所有选择,然后由用户键入3个字符开始的所有项.

I have also implemented auto complete when the user types in 3 chars in the combobox, the drop down will open showing all the selections first, then then all the items starting from the 3 chars type in by the user.

我已经研究并实现了以下代码,并且可以正常工作,但是我想知道这是否是最好的方法,还是可以更好地实现呢?代码是:

I have researched and implemented the following code and it is working fine, but i want to know whether this is the best approach or can i implement this in a better manner, code is :

        IEnumerable<MyData> sort;
        ObservableCollection<MyData> tempSortedCities = new ObservableCollection<MyData>();
        sort = City.OrderByDescending(item => item.IsSelected).ThenBy(item => item.Name.ToUpper()) ; 
       // City is my observablecollection<MyData> property in my Model binded to combobox in UI
        foreach (var item in sort)
            tempSortedCities.Add(item);


        City.Clear(); // City is my observablecollection<MyData> property in my Model
        City = tempSortedCities;
        tempSortedCities = null;
        sort = null;  

提前感谢您的时间!

推荐答案

ICollectionView似乎很适合.它是专为在不修改原始集合的情况下对集合进行排序,过滤和分组而设计的.

ICollectionView seems to be a perfect fit for this. It was designed specifically for sorting, filtering and grouping of a collection without modifying the original collection.

您可以使用以下代码为您的集合获取ICollectionView的实例:

You can get an instance of ICollectionView for your collection using the following code:

var sortedCities  = CollectionViewSource.GetDefaultView(City);

然后,您可以通过将SortDescription类型的实例添加到ICollectionView.SortDescriptions集合中来设置排序:

Then you can setup sorting by adding instances of SortDescription type to the ICollectionView.SortDescriptions collection:

sortedCities.SortDescriptions.Add(new SortDescription("IsSelected", ListSortDirection.Descending));
sortedCities.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));

然后,您可以将ComboBox直接绑定到集合视图(而不是City集合),它将显示已排序的数据.

Then you can bind your ComboBox directly to the collection view (instead of City collection) and it will display already sorted data.

这篇关于对ObservableCollection进行排序-最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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