Comparison Delegate in C#

How to Sort a List of the Complex Type using Comparison Delegate

In this article, I am going to discuss How to Sort a List of the Complex Type using Comparison Delegate in C# with Examples. Please read our previous article where we discussed How to Sort a List of the Complex Type in C#with Examples.

List<T> Class Sort Method in C#:

The Generic List Collection Class in C# provides the following four Sort Methods.

  1. Sort(): This method is used to sort the elements in the entire Generic List using the default comparer.
  2. Sort(IComparer<T>? comparer): This method is used to sort the elements in the entire Generic List using the specified comparer.
  3. Sort(Comparison<T> comparison): This method is used to sort the elements in the entire Generic List using the specified System.Comparison.
  4. Sort(int index, int count, IComparer<T>? comparer): This method is used to sort the elements in a range of elements in a Generic List using the specified comparer.

If you notice, the Sort(Comparison<T> comparison) method in the List class expects the Comparison delegate to be passed as an argument. Let us understand this overloaded version.

Now, right-click on the Comparison Delegate and then select go to definition, then you will see the following definition of Comparison Delegate in C#.

How to Sort a List of the Complex Type using Comparison Delegate in C# with Examples

What is Comparison<T> Delegate in C#?

The Comparison Delegate represents the method that compares two objects of the same type. Here, the parameter x is the first object to compare. The ]parameter y is the second object to compare. And “T” here represents the type of objects to compare. It returns a signed integer that indicates the relative values of x and y, as shown in the following table.

  1. Return value greater than ZERO – x is greater than y.
  2. Return value less than ZERO – x is less than y
  3. The Return value is ZERO – x equals y

Now, let us proceed and see how we can use the Comparison delegate

Approach1:

Step1: Create a function whose signature must match the signature of the 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 the Sort() method that expects the Comparison delegate as a parameter as follows.
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 am going to discuss Generic Dictionary<TKey, TValue> Collection Class in C# with Examples. Here, In this article, I try to explain How to Sort a List of the Complex Type in C# using Comparison Delegate with Examples. I hope this How to Sort a List of the Complex Type using Comparison Delegate in C# with Examples article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

1 thought on “Comparison Delegate in C#”

Leave a Reply

Your email address will not be published.