Comparison Delegate in C#

Comparison delegate in C#

In this article, I will discuss how to sort a list of the complex type using Comparison Delegate 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:
OUTPUT:

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

Approach2:

In Approcah1 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.

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.
OUTPUT:

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

SUMMARY:

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 *