List 클래스의 Sort() 메서드 오버로드는 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