如何在C#中使用比较委托对复杂类型列表进行排序?
Sort()
List类中方法的重载期望将比较委托作为参数传递。
公共无效排序(Comparison<T>比较)
CompareTo返回一个整数,该整数指示此实例的值是否小于,等于或大于指定对象或另一个Int16实例的值。
C#中的Int16.CompareTo()方法用于将此实例与指定对象或另一个Int16实例进行比较。
示例
class Program{ public static void Main(){ Employee Employee1 = new Employee(){ ID = 101, Name = "Mark", Salary = 4000 }; Employee Employee2 = new Employee(){ ID = 103, Name = "John", Salary = 7000 }; Employee Employee3 = new Employee(){ ID = 102, Name = "Ken", Salary = 5500 }; List<Employee> listEmployees = new List<Employee>(); listEmployees.Add(Employee1); listEmployees.Add(Employee2); listEmployees.Add(Employee3); Console.WriteLine("Employees before sorting"); foreach (Employee Employee in listEmployees){ Console.WriteLine(Employee.ID); } listEmployees.Sort((x, y) => x.ID.CompareTo(y.ID)); Console.WriteLine("Employees after sorting by ID"); foreach (Employee Employee in listEmployees){ Console.WriteLine(Employee.ID); } listEmployees.Reverse(); Console.WriteLine("Employees in descending order of ID"); foreach (Employee Employee in listEmployees){ Console.WriteLine(Employee.ID); } } //方法1-步骤1- //包含比较雇员的逻辑的方法 private static int CompareEmployees(Employee c1, Employee c2){ return c1.ID.CompareTo(c2.ID); } } public class Employee{ public int ID { get; set; } public string Name { get; set; } public int Salary { get; set; } }
输出结果
Employees before sorting 101 103 102 Employees after sorting by ID 101 102 103 Employees in descending order of ID 103 102 101