C# 中集合类型需要按多个条件排序
2018-08-20 15:52
1681 查看
在 C# (.net 3.5 之后) 中集合是可以通过 OrderBy() 和 OrderByDescending()方法来进行排序的,
如果需要集合中的元素是对象,还可以通过 Lambda表达式进行按属性排序,如:
定义一个学生类:
class student { public int id { get; set; } public string name { get; set; } public string hometown { get; set; } public student(int id, string name, string hometowm) { this.id = id; this.name = name; this.hometown = hometown; } }
按学生名字排序,如果同名的,则按学号升序排序:
List<student> list = new List<student>() { new student(101, "olivia", "shantou"), new student(102, "sarah","shanghai"), new student(103, "nani", "china"), new student(104, "tommy", "maoming"), new student(105, "tommy", "shandong"), };
listBox.ItemsSource = list.OrderBy(x => x.name); // just order by name
listBox2.ItemsSource = list.OrderBy(x => x.name).ThenByDescending(x => x.id); // order by name, and then order desc by id
}
由上可见,多个条件时使用的是 ThenBy() 以及 ThenByDescending() 方法
结果:
只按 name 排序:
先按 name 排序,再按 id 逆序:
相关文章推荐
- 1.提取List<bean>中的某属性集合; 2.List<bean>排序(需要指定升序降序和排序字段的类型)
- [c#基础]泛型集合的自定义类型排序
- List泛型自定义类型排序和大小比较C#版
- c#基础之集合 类型总结
- C#中List或其它集合对象排序方法的一点理解
- 【Redis缓存机制】7.SortSet排序集合类型操作
- c#基础知识---集合之排序列表(SortedList)
- C#读取其他运行的Exe上面的控件类型集合
- .NET/C#中对自定义对象集合进行自定义排序的方法
- Go语言使用sort包对任意类型元素的集合进行排序的方法
- 【Redis缓存机制】7.SortSet排序集合类型操作
- C#调用C++版本dll时的类型转换需要注意的问题小结
- 【Redis缓存机制】7.SortSet排序集合类型操作
- C#集合类型总结和性能分析
- c# 集合、存储及排序、迭代
- C# 3.0新特性初步研究 Part4:使用集合类型初始化器_C#教程
- C# 通过IEnumberable接口和IEnumerator接口实现自定义集合类型foreach功能
- C# 3.0新特性初步研究 Part4:使用集合类型初始化器
- C#中利用LINQ to XML与反射把任意类型的泛型集合转换成XML格式字符串的方法
- mongo 对数据很严格 在使用组装条件的时候需要注意 字段的类型, 分享几个转换的函数