IComparable interface is a great way to sort your objects by using the sorting routines of the List. There is a another interface called IComparer<T> which allows the objects to be sorted based on different criteria.
How to make a Type Sortable on Different Criteria in C# ?
For example , if you wanted to sort the Employee objects by Id , you can create a new class called CompareId which implements the IComparer<Employee> interface as shown below.
public class CompareId : IComparer<Employee> { public int Compare(Employee x, Employee y) { return x.Id.CompareTo(y.Id); } }
When you sort the List , you pass the instance of the CompareId class to the sort method of the List.
CompareId objId = new CompareId(); employees.Sort(objId);
The complete sourcecode of the example of Icomparer interface demo is below.
using System; using System.Collections.Generic; namespace ConsoleApplication5 { public class CompareId : IComparer<Employee> { public int Compare(Employee x, Employee y) { return x.Id.CompareTo(y.Id); } } public class Employee : IComparable<Employee> { public string Name { get; set; } public string Department { get; set; } public int Id { get; set; } public int Age { get; set; } public Employee(string name, int id, int age, string department) { this.Age = age; this.Name = name; this.Department = department; this.Id = id; } // Implement the CompareTo method of IComparable interface public int CompareTo(Employee other) { return this.Age.CompareTo(other.Age); } } class Program { static void Main(string[] args) { List<Employee> employees = new List<Employee>(); Employee emp1 = new Employee("Vijay",189,45,"Technology"); Employee emp2 = new Employee("Ajith Kumar", 120, 50, "Design"); Employee emp3 = new Employee("Surya", 201, 40, "Testing"); employees.Add(emp1); employees.Add(emp2); employees.Add(emp3); foreach(var item in employees) Console.WriteLine(item.Name); Console.WriteLine("-After Sorting-"); // Id Comparer - instance creation CompareId objId = new CompareId(); employees.Sort(objId); foreach(var item in employees) Console.WriteLine(item.Name); Console.ReadLine(); } } }
Leave a Reply