C# 中使用Linq和Lambda表达式对List<T>进行排序

来源:互联网 发布:java代码审查表 编辑:程序博客网 时间:2024/05/21 17:04

C#中List<T>排序的两种方法


List<Student> stu = (List<Student>)Session["StudentList"];


Linq表达式:
//按学号降序
List<Student> stuList = (from s instu orderby s.stuNOdescending select s).ToList<Student>();

//按学号升序
List<Student> stuList = (from s instu orderby s.stuNO  select s).ToList<Student>();


使用Lambda表达式排序:
//按学号降序
单字段:List<StudentstuList= stu.OrderByDescending(s=> s.orderid).ToList<Student>();
多字段:List<StudentstuList= stu.OrderByDescending(s=> new{s.stuNO,s.stuName}).ToList<Student>();

//按学号升序
单字段:List<StudentstuList= stu.OrderBy(s=> s.stuNO).ToList<Student>();
多字段:List<StudentstuList= stu.OrderBy(s=> new{s.stuNO,s.stuName}).ToList<Student>();


多字段主次顺序排序情况,先按no排序,再按name排序
List<StudentstuList= stu.OrderBy(s=> s.stuNO).ThenBy(s=> s.stuName).ToList<Student>();

List<StudentstuList= stu.OrderBy(s=> new{ s.stuNO }).ThenBy(s=> new{s.stuName}).ToList<Student>();




0 0
原创粉丝点击