首頁 >後端開發 >C#.Net教程 >如何使用 C# 中的比較委託對複雜類型清單進行排序?

如何使用 C# 中的比較委託對複雜類型清單進行排序?

WBOY
WBOY轉載
2023-08-28 08:05:021012瀏覽

如何使用 C# 中的比较委托对复杂类型列表进行排序?

List 類別中 Sort() 方法的重載需要 Comparison 委託 作為參數傳遞。

public void Sort(Comparison Comparison)

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);
      }
   }
   // Approach 1 - Step 1
   // Method that contains the logic to compare Employees
   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

以上是如何使用 C# 中的比較委託對複雜類型清單進行排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除