Sorting List Of Complex Types In C#

Introduction

This article is related to the 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.

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(); // Error line
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.

error function

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 this.

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 on the Id property.

Now if we want to sort the list based on 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);
    }
}

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 on name.


Similar Articles