C# 中使用Linq和Lambda表示式對List進行排序

jett010發表於2018-04-27

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<Student> stuList= stu.OrderByDescending(s=> s.orderid).ToList<Student>();
多欄位:List<Student> stuList= stu.OrderByDescending(s=> new{s.stuNO,s.stuName}).ToList<Student>();

//按學號升序
單欄位:List<Student> stuList= stu.OrderBy(s=> s.stuNO).ToList<Student>();
多欄位:List<Student> stuList= stu.OrderBy(s=> new{s.stuNO,s.stuName}).ToList<Student>();

多欄位主次順序排序情況,先按no排序,再按name排序
List<Student> stuList= stu.OrderBy(s=>
s.stuNO).ThenBy(s=>
s.stuName).ToList<Student>();

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

相關文章