How to Sort a List of Complex Type in C#

How to Sort a List of Complex Type in C#

In this article, I am going to discuss how to sort a list of Complex Type in C# like Employee, Customer, Product, Department, etc. with example. Please read our previous article before proceeding to this article where we discussed how to sort a list of simple types in C# like int, double, decimal, string, etc. with an example.

In our last article, we discussed that sorting a list of simple types like int, double, char, string, etc. is straight forward. Means we just need to invoke the Sort() method (Provided by the Generic List class) on the list instance and the data will be automatically sorted in ascending order. For example, if we have a list of integers as shown below

List<int> numbersList = new List<int>{ 1, 8, 7, 5, 2, 3, 4, 9, 6 };

Then we need to invoke the Sort() method on numbers list collection as shown below

numbersList.Sort();

However, when we do the same thing on a complex type like Employee, Product, Customer, Department, etc. we get a runtime exception as “invalid operation exception – Failed to compare 2 elements in the array”. 

Example:

In the following example we will not get ant Compile Time Error. But the Invoking Sort() on a list of complex types will throw runtime exception i.e. invalid operation exception unless we implement the IComparable interface.

using System;
using System.Collections.Generic;
namespace ListCollectionSortReverseMethodDemo
{
    public class Program
    {
        public static void Main()
        {
            Employee emp1 = new Employee()
            {
                ID = 101,
                Name = "Pranaya",
                Gender = "Male",
                Salary = 5000
            };
            Employee emp2 = new Employee()
            {
                ID = 102,
                Name = "Priyanka",
                Gender = "Female",
                Salary = 7000
            };
            Employee emp3 = new Employee()
            {
                ID = 103,
                Name = "Anurag",
                Gender = "Male",
                Salary = 4500
            };
            Employee emp4 = new Employee()
            {
                ID = 104,
                Name = "Sambit",
                Gender = "Male",
                Salary = 6500
            };
            Employee emp5 = new Employee()
            {
                ID = 105,
                Name = "Hina",
                Gender = "Female",
                Salary = 7500
            };
            Employee emp6 = new Employee()
            {
                ID = 106,
                Name = "Tarun",
                Gender = "Male",
                Salary = 6000
            };
            List<Employee> listEmployees = new List<Employee>();
            listEmployees.Add(emp1);
            listEmployees.Add(emp2);
            listEmployees.Add(emp3);
            listEmployees.Add(emp4);
            listEmployees.Add(emp5);
            listEmployees.Add(emp6);
            Console.WriteLine("Employees before sorting");
            foreach (Employee employee in listEmployees)
            {
                Console.WriteLine("ID = {0}, Name = {1},  Gender = {2}, Salary = {3}",
                    employee.ID, employee.Name, employee.Gender, employee.Salary);
            }
            
            listEmployees.Sort();
            Console.WriteLine("Employees After sorting");
            foreach (Employee employee in listEmployees)
            {
                Console.WriteLine("ID = {0}, Name = {1},  Gender = {2}, Salary = {3}",
                    employee.ID, employee.Name, employee.Gender, employee.Salary);
            }
            Console.ReadKey();
        }
    }
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }
    }
}

When we execute the above code, it will give us the below runtime exception.

How to Sort a List of Complex Type in C#

To sort a list of complex types without using LINQ, the complex type has to implement the IComparable interface and need to provide the implementation for the CompareTo() method. The CompareTo() method returns an integer value and the meaning of the return value as shown below.

  1. Return value greater than ZERO – The current instance is greater than the object being compared with.
  2. Return value less than ZERO – The current instance is less than the object being compared with.
  3. The Return value is ZERO – The current instance is equal to the object being compared with.

Alternatively, we can also invoke the CompareTo() method directly. The Salary property of the Employee object is int and the CompareTo() method is already implemented on integer type that we already discussed in our previous article, so we can invoke this method and return it’s valued as shown below.

return this.Salary.CompareTo(obj.Salary);

Let see an example for better understanding.

Modify the Employee class as shown below.
public class Employee : IComparable<Employee>
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public int Salary { get; set; }
    public int CompareTo(Employee obj)
    {
        if (this.Salary > obj.Salary)
        {
            return 1;
        }
        else if (this.Salary < obj.Salary)
        {
            return -1;
        }
        else
        {
            return 0;
        }
    }
}

Now run the application. It will give you the result in ascending order based on the Employee Salary as shown in the below image.

How to Sort a List of Complex Type in C#

If you prefer not to use the Sort functionality provided by the Employee class, then you can provide your own implementation by implementing the IComparer interface. For example, if you want the employees to be sorted by the name instead of salary then you need to follow the below two steps.

Step1: Implement the IComparer interface
public class SortByName : IComparer<Employee>
{
    public int Compare(Employee x, Employee y)
    {
        return x.Name.CompareTo(y.Name);
    }
}

Step2: Pass an instance of the class that implements the IComparer interface as an argument to the Sort() method as shown below.

SortByName sortByName = new SortByName();
listEmployees.Sort(sortByName);

Here is the complete code:

Following are the SortByName and Employee classes:

public class SortByName : IComparer<Employee>
{
    public int Compare(Employee x, Employee y)
    {
        return x.Name.CompareTo(y.Name);
    }
}
public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public int Salary { get; set; }
}

Following is the Program class:

using System;
using System.Collections.Generic;
namespace ListCollectionSortReverseMethodDemo
{
    public class Program
    {
        public static void Main()
        {
            Employee emp1 = new Employee()
            {
                ID = 101,
                Name = "Pranaya",
                Gender = "Male",
                Salary = 5000
            };
            Employee emp2 = new Employee()
            {
                ID = 102,
                Name = "Priyanka",
                Gender = "Female",
                Salary = 7000
            };
            Employee emp3 = new Employee()
            {
                ID = 103,
                Name = "Anurag",
                Gender = "Male",
                Salary = 4500
            };
            Employee emp4 = new Employee()
            {
                ID = 104,
                Name = "Sambit",
                Gender = "Male",
                Salary = 6500
            };
            Employee emp5 = new Employee()
            {
                ID = 105,
                Name = "Hina",
                Gender = "Female",
                Salary = 7500
            };
            Employee emp6 = new Employee()
            {
                ID = 106,
                Name = "Tarun",
                Gender = "Male",
                Salary = 6000
            };
            List<Employee> listEmployees = new List<Employee>();
            listEmployees.Add(emp1);
            listEmployees.Add(emp2);
            listEmployees.Add(emp3);
            listEmployees.Add(emp4);
            listEmployees.Add(emp5);
            listEmployees.Add(emp6);
            Console.WriteLine("Employees before sorting");
            foreach (Employee employee in listEmployees)
            {
                Console.WriteLine("ID = {0}, Name = {1},  Gender = {2}, Salary = {3}",
                    employee.ID, employee.Name, employee.Gender, employee.Salary);
            }
            SortByName sortByName = new SortByName();
            listEmployees.Sort(sortByName);
            Console.WriteLine("Employees After sorting");
            foreach (Employee employee in listEmployees)
            {
                Console.WriteLine("ID = {0}, Name = {1},  Gender = {2}, Salary = {3}",
                    employee.ID, employee.Name, employee.Gender, employee.Salary);
            }
            Console.ReadKey();
        }
    }
}

Now run the application and should give the following output.

How to Sort a List of Complex Type in C#

In the next article, I am going to discuss the comparison delegate in C# with an example. Here, in this article, I try to explain how to sort a list of Complex type in C# with an example. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

6 thoughts on “How to Sort a List of Complex Type in C#”

    1. Not sure If I did it properly…


      using System.Collections.Generic;
      using static System.Console;

      namespace UnderstandingListSorting
      {
      public class Program
      {
      public static void Main()
      {
      List listEmployees = new List()
      {
      new Employee() {ID = 101, Name = "Pranaya", Gender = "Male", Salary = 5000},
      new Employee() {ID = 102, Name = "Priyanka", Gender = "Female", Salary = 7000},
      new Employee() {ID = 103, Name = "Anurag", Gender = "Male", Salary = 4500},
      new Employee() {ID = 104, Name = "Sambit", Gender = "Male", Salary = 6500},
      new Employee() {ID = 105, Name = "Hina", Gender = "Female", Salary = 7500},
      new Employee() {ID = 106, Name = "Tarun", Gender = "Male", Salary = 6000}
      };

      WriteLine("Employees before sorting");
      foreach (Employee employee in listEmployees)
      {
      WriteLine($"ID = {employee.ID}, Name = {employee.Name}, Gender = {employee.Gender}, Salary = {employee.Salary}");
      }

      SortBySalary sortBySalary = new SortBySalary();
      listEmployees.Sort(sortBySalary);

      WriteLine("Employees after sorting - by salary");
      foreach (Employee employee in listEmployees)
      {
      WriteLine($"ID = {employee.ID}, Name = {employee.Name}, Gender = {employee.Gender}, Salary = {employee.Salary}");
      }

      SortByName sortByName = new SortByName();
      listEmployees.Sort(sortByName);

      WriteLine("Employees after sorting - by name");
      foreach (Employee employee in listEmployees)
      {
      WriteLine($"ID = {employee.ID}, Name = {employee.Name}, Gender = {employee.Gender}, Salary = {employee.Salary}");
      }

      ReadKey();
      }
      }
      public class Employee
      {
      public int ID { get; set; }
      public string Name { get; set; }
      public string Gender { get; set; }
      public int Salary { get; set; }
      }
      public class SortBySalary : IComparer
      {
      int IComparer.Compare(Employee x, Employee y)
      {
      if (x.Salary.CompareTo(y.Salary) != 0)
      {
      return x.Salary.CompareTo(y.Salary);
      }
      else
      {
      return 0;
      }
      }
      }
      public class SortByName : IComparer
      {
      int IComparer.Compare(Employee x, Employee y)
      {
      if (x.Name.CompareTo(y.Name) != 0)
      {
      return x.Name.CompareTo(y.Name);
      }
      else
      {
      return 0;
      }
      }
      }
      }

  1. Loknadh.Ravineni

    I have tried the below code worked for me !!!!

    static void Main(string[] args)
    {
    Employee emp1 = new Employee()
    {
    ID = 101,
    Name = “Pranaya”,
    Gender = “Male”,
    Salary = 5000
    };
    Employee emp2 = new Employee()
    {
    ID = 102,
    Name = “Priyanka”,
    Gender = “Female”,
    Salary = 7000
    };
    Employee emp3 = new Employee()
    {
    ID = 103,
    Name = “Anurag”,
    Gender = “Male”,
    Salary = 5500
    };
    Employee emp4 = new Employee()
    {
    ID = 104,
    Name = “Sambit”,
    Gender = “Male”,
    Salary = 6500
    };
    Employee emp5 = new Employee()
    {
    ID = 105,
    Name = “Hina”,
    Gender = “Female”,
    Salary = 7500
    };
    Employee emp6 = new Employee()
    {
    ID = 106,
    Name = “Tarun”,
    Gender = “Male”,
    Salary = 8500
    };
    List firstlist = new List();
    Console.WriteLine(“Using Add method to add the data to the list”);
    Console.WriteLine();
    firstlist.Add(emp1);
    firstlist.Add(emp2);
    firstlist.Add(emp3);

    foreach (var item in firstlist)
    {
    Console.WriteLine($”Id:{item.ID}, Name:{item.Name}, Gender:{item.Gender}, Salary:{item.Salary}”);
    }
    Console.WriteLine();
    Console.WriteLine(“items present in the list before sorting list”);
    Console.WriteLine();
    firstlist.Sort();

    Console.WriteLine(“The elements of the list is after Sorting is “);

    foreach (var item2 in firstlist)
    {
    Console.WriteLine($”Id:{item2.ID}, Name:{item2.Name}, Gender:{item2.Gender}, Salary:{item2.Salary}”);
    }

    Console.ReadLine();

    }

    public class Employee:IComparable
    {
    public int ID { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public int Salary { get; set; }

    public int CompareTo(Employee other)
    {
    return this.ID.CompareTo(other.ID);
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *