C# Linq orderby排序很好用,可以方便的对一个C#数组集合等进行顺序或倒序排序,分别用到了Linq的ascending和descending属性,Linq包含以下分类排序运算符,如下:
| 排序操作属性 | 描述 |
|---|---|
| OrderBy | 根据指定的字段以升序或降序排列集合中的元素。 |
| OrderByDescending | 根据指定的字段以降序排列集合,只在方法语法中有效。 |
| ThenBy | 只在方法语法中有效,用于按升序进行二级分类。 |
| ThenByDescending | 只在方法语法中有效,用于降序排列的二级分类。 |
| Reverse | 只在方法语法中有效,按相反顺序对集合进行排序。 |
Linq OrderBy默认是ascending顺序排序的,因此ascending属性可以省略,我们下面的示例是使用Linq对Student学生类的List集合进行顺序与倒序排序,代码如下:
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentID = 2, StudentName = "Steve", Age = 15 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 }
};
//顺序排序
var orderByResult = from s in studentList
orderby s.StudentName ascending //ascending可以省略
select s;
//倒序排序
var orderByDescendingResult = from s in studentList
orderby s.StudentName descending
select s;至于对Linq排序后的结果,这里就不展示了,c# Linq还有很多用法,这里只展示Linq排序部分。