IComparer<T> is commonly used multi-level sorting (also called secondary sorting, compound sorting, or lexicographical sorting).
The idea is:
- Compare by the primary field
- If equal (result == 0), compare by the secondary field
- Continue until a difference is found
Example: Sort Employee by Department → Name → Salary
class Employee
{
public string Name { get; set; } = "";
public string Department { get; set; } = "";
public double Salary { get; set; }
}
class EmployeeComparer : IComparer<Employee>
{
public int Compare(Employee? x, Employee? y)
{
if (x == null && y == null) return 0;
if (x == null) return -1;
if (y == null) return 1;
// Level 1: Department
int result = string.Compare(
x.Department,
y.Department,
StringComparison.OrdinalIgnoreCase);
if (result != 0)
return result;
// Level 2: Name
result = string.Compare(
x.Name,
y.Name,
StringComparison.OrdinalIgnoreCase);
if (result != 0)
return result;
// Level 3: Salary
return x.Salary.CompareTo(y.Salary);
}
}
class Program
{
static void Main()
{
List<Employee> employees = new List<Employee>
{
new Employee { Name = "Alice", Department = "HR", Salary = 50000 },
new Employee { Name = "Bob", Department = "IT", Salary = 60000 },
new Employee { Name = "Charlie", Department = "HR", Salary = 55000 },
new Employee { Name = "David", Department = "IT", Salary = 65000 },
new Employee { Name = "Eve", Department = "HR", Salary = 50000 }
};
employees.Sort(new EmployeeComparer());
foreach (var employee in employees)
{
Console.WriteLine($"{employee.Department} - {employee.Name} - ${employee.Salary}");
}
}
}
HR - Alice - $50000
HR - Charlie - $55000
HR - Eve - $50000
IT - Bob - $60000
IT - David - $65000
Tips. Practically we use LINQ which is often cleaner:
var sorted = employees
.OrderBy(e => e.Department)
.ThenBy(e => e.Name)
.ThenBy(e => e.Salary);
No comments:
Post a Comment