#unity/日常积累 LINQ中的排序操作符,包括:OrderBy、OrderByDescending、ThenBy、ThenByDescending、Reverse,提供了升序或者降序排序。 OrderBy:按升序对序列的元素进行排序。 OrderByDescending:按降序对序列的元素排序。 ThenBy:按升序对序列中的元素执行后续排序。 ThenByDescending:按降序对序列中的元素执行后续排序。 Reverse:反转序列中元素的顺序。 示例:将员工列表进行排序,排序要求: 1、按部门编号升序; 2、按员工薪资降序; 3、按员工入职时间升序; 方式一: ``` cs empList = empList.OrderBy(a => a.DeptID).ThenByDescending(a => a.Salary).ThenBy(a => a.EntryTime).ToList(); ``` **方式二:** ``` cs empList = (from emp in empList orderby emp.DeptID ascending, emp.Salary descending, emp.EntryTime ascending select emp).ToList(); ``` **完整代码:** ``` cs static void Main(string[] args) { //获取员工列表 List empList = GetEmployeeList(); //打印排序前列表 System.Console.WriteLine("排序前:"); empList.ForEach(a => System.Console.WriteLine(a.ToString())); //使用LINQ执行排序 empList = empList.OrderBy(a => a.DeptID).ThenByDescending(a => a.Salary).ThenBy(a => a.EntryTime).ToList(); //打印排序后列表 System.Console.WriteLine(""); System.Console.WriteLine("排序后:"); empList.ForEach(a => System.Console.WriteLine(a.ToString())); System.Console.ReadLine(); } /// /// 获取员工列表 /// public static List GetEmployeeList() { List result = new List(); result.Add(new Employee() { Name = "张伟伟", DeptID = 3, DeptName = "市场部", Salary = 1500, EntryTime = DateTime.Parse("2016-05-12")}); result.Add(new Employee() { Name = "李涛涛", DeptID = 2, DeptName = "财务部", Salary = 1600, EntryTime = DateTime.Parse("2017-02-16") }); result.Add(new Employee() { Name = "王亮亮", DeptID = 1, DeptName = "研发部", Salary = 1900, EntryTime = DateTime.Parse("2018-10-25") }); result.Add(new Employee() { Name = "孙红红", DeptID = 1, DeptName = "研发部", Salary = 1900, EntryTime = DateTime.Parse("2018-08-03") }); result.Add(new Employee() { Name = "黄苗苗", DeptID = 3, DeptName = "市场部", Salary = 2200, EntryTime = DateTime.Parse("2016-09-06") }); result.Add(new Employee() { Name = "蔡明明", DeptID = 1, DeptName = "研发部", Salary = 3500, EntryTime = DateTime.Parse("2012-11-25") }); result.Add(new Employee() { Name = "吴慧慧", DeptID = 2, DeptName = "财务部", Salary = 1800, EntryTime = DateTime.Parse("2018-07-26") }); result.Add(new Employee() { Name = "杨梅梅", DeptID = 3, DeptName = "市场部", Salary = 2200, EntryTime = DateTime.Parse("2017-02-15") }); return result; } ``` 创建员工信息类(Emplayee.cs) ``` cs /// /// 员工信息类 /// public class Employee { /// /// 员工名称 /// public string Name { get; set; } /// /// 部门编号 /// public int DeptID { get; set; } /// /// 部门名称 /// public string DeptName { get; set; } /// /// 薪资 /// public decimal Salary { get; set; } /// /// 入职时间 /// public DateTime EntryTime { get; set; } public override string ToString() { return String.Format("{0};{1};薪资:{2}元;入职时间:{3};", this.Name, this.DeptName, this.Salary, this.EntryTime.ToString("yyyy-MM-dd")); } } ``` 执行结果如下图: ![[Pasted image 20240122142802.png]]