Comparison Delegate in C#

Comparison delegate in C#

In this article, I am going to discuss how to sort a list of the complex type using Comparison Delegate in C#. Please read our previous article where we discussed how to sort a list of Complex Type in C#.

One of the overload version of the Sort() method in List class expects Comparison delegate to be passed as an argument. Let us understand this overloaded version. The syntax is shown below.

public void Sort(Comparison<T> comparison)

Below is the definition of Comparison Delegate.

sorting a list of the Complex type in C# using Comparison Delegate

Approach1:

Step1: Create a function whose signature must match with the signature of Comparison delegate. This is the method where we need to write the logic to compare 2 employee objects.

private static int CompareEmployees(Employee e1, Employee e2)
{
    return return e1.Gender.CompareTo(e2.Gender);
}

Step2: Create an instance of Comparison delegate, and then pass the name of the function created in Step1 as the argument. So, at this point “Comparison” delegate is pointing to our function that contains the logic to compare 2 employee objects.

Comparison<Employee> employeeComparer= new Comparison<Employee>(CompareEmployees);

Step3: Pass the delegate instance as an argument, to Sort() method.

listEmployees.Sort(employeeComparer);

At this point, listEmployees should be sorted using the logic defined in CompareEmployees() function. Below is the complete code:

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);
            }
            Comparison<Employee> employeeComparer = new Comparison<Employee>(CompareEmployees);

            listEmployees.Sort(employeeComparer);

            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();
        }

        private static int CompareEmployees(Employee e1, Employee e2)
        {
            return e1.Gender.CompareTo(e2.Gender);
        }
    }
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }
    }
}
OUTPUT:

sorting a list of the Complex type in C# using Comparison Delegate

Approach2:

In Approach1 this is what we have done

  1. We have Created a private function that contains the logic to compare the employees
  2. Then created an instance of Comparison delegate, and then passed the name of the private function to the delegate.
  3. Finally passed the delegate instance to the Sort() method.
Do we really have to follow all these steps? Isn’t there any other way? 

The above code can be simplified using the delegate keyword as shown below which is also known as an anonymous method.

listEmployees.Sort(delegate (Employee e1, Employee e2)
                            {
                                return e1.Gender.CompareTo(e2.Gender);
                            });
Approach3: 

The code in Approach2 can be further simplified using the lambda expression as shown below.

listCutomers.Sort((x, y) => x.ID.CompareTo(y.ID));

The complete code for Approach2 and 3 is given below.
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);
            }
           
            //Apprach2
            //Using Anonymous methid
            //listEmployees.Sort(delegate (Employee e1, Employee e2)
            //                {
            //                    return e1.Gender.CompareTo(e2.Gender);
            //                });

            //Approach3
            //using Lambda Expression
            listEmployees.Sort((x, y) => x.Gender.CompareTo(y.Gender));

            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; }
    }
}
OUTPUT:

sorting a list of the Complex type in C# using Comparison Delegate

In this article, I try to explain sorting a list of the Complex type in C# using Comparison Delegate with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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