Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách Sắp Xếp Danh Sách Kiểu Phức Tạp Dùng Comparison Delegate Trong C#


Các overload của phương thức Sort() trong lớp List mong đợi delegate Comparison được truyền làm tham số.

public void Sort(Comparison<T> comparison)

CompareTo trả về số nguyên chỉ ra xem giá trị của thể hiện này nhỏ hơn, bằng, hay lớn hơn giá trị của đối tượng được chỉ định hoặc thể hiện Int16 khác.

Phương thức Int16.CompareTo() trong C# dùng để so sánh thể hiện này với một đối tượng được chỉ định hoặc thể hiện Int16 khác.

Ví Dụ

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); 
        } 
    } 
    // Cách 1 - Bước 1 
    // Phương thức chứa logic so sánh Employee 
    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; } 
}

Kết Quả

Employees before sorting 
101 
103 
102 
Employees after sorting by ID 
101 
102 
103 
Employees in descending order of ID 
103 
102 
101