This article is related to sorting of lists in C# containing complex objects. Through this article we will understand the use of two different interfaces of C#. If we have a list built of primitive types like integer, string and so on and if we call the sort method over that list then we will get a sorted list. But if our list contains complex objects then if we call a sort method over that list then we will get an error. This is because on calling the sort method the list does not know how to sort a complex object because that complex object may contain various fields or properties.
I have created a class Employee as in the following:
- class Employee
- {
- public int Id { get; set; }
- public string Name { get; set; }
- }
If I create a list of Type Employee and add some objects in that like:
- List<Employee> employeeList = new List<Employee>();
- Employee ob = new Employee();
- ob.Id = 2;
- ob.Name = "Ritesh";
- employeeList.Add(ob);
- ob = new Employee();
- ob.Id = 1;
- ob.Name = "Sophi";
- employeeList.Add(ob);
- ob = new Employee();
- ob.Id = 3;
- ob.Name = "Aman";
- employeeList.Add(ob);
- employeeList.Sort();
- foreach (var item in employeeList)
- {
- Console.WriteLine(item.Id + " " + item.Name);
- }
Then on calling the sort method over the list we will get the following error:
Now if we want to sort the list of complex objects then we need to implement the IComparable interface that gives us a CompareTo method. Now our class will look like:
- Class Employee : IComparable<Employee>
- {
- Public int Id { get; set; }
- Public string Name { get; set; }
- Public int CompareTo(Employee other)
- {
- return this.Id.CompareTo(other.Id);
- }
- }
In this class we have compared the objects using an Id property of the class so on calling the sort method of the list we will get the sorted list based upon Id property.
Now if we want to sort the list based upon the Name property then we must implement something different. We need an IComparer interface that provides a mechanism for additional comparisons. This interface has two versions, a simple one and a generic one. Generic is preferred since it prevents boxing and unboxing of objects. So to implement the IComparer interface we will create another class that implements the IComparer interface of type Employee.
- class EmployeeSortByName : IComparer<Employee>
- {
- public int Compare(Employee x, Employee y)
- {
- return x.Name.CompareTo(y.Name);
- }
- }
In the preceding class we have a Compare method with the two parameters x and y. The Compare method internally calls the CompareTo method to compare the objects by name.
So now if we want to sort the list then we will modify our Sort method and call it like:
- employeeList.Sort(new EmployeeSortByName());
And we will get a sorted list based upon name.