C# ObservableCollection两个字段排序的情况

相对于System.Linq的OrderBy及OrderByDescending方法,调用后产生IOrderedEnumberable对象,这个对象为排序后的返回值,但原对象未发生变化。

试想,有这种需求,ObservableCollection调用排序方法后,此对象也跟着排序,怎么做呢?只能自己写个扩展方法了,方法内使用的冒泡排序算法,非常简单,当然使用是更简单、方便了。

注意:将方法写为扩展方法更方便:

class Student

{

int id;

string name;

}

ObservableCollection listDatas=new ObservableCollection<Student>();

listData .Add(new Student(){id=2,name="xiaoming"};

listData.Add(new Student(){id=1,name="李华"};

listData.Add(new Student(){id=3,name="张度"};

listDatas.OrderBy(cu=>cu.id,true);//按ID升序排序

listDatas.OrderBy(cu=>cu.id,false);//按ID降序排序

listDatas.OrderBy(cu=>cu.name,false);//按名称升序排序 

listDatas..ThenBy(x => x.name)//按名称升序排序 (只有ID相同的情况下,按name升序排序)          

猜你喜欢

转载自www.cnblogs.com/wlming/p/10895043.html
今日推荐