This post will discuss how to sort a list of objects using some property in C#.

C# has a built-in Sort() method that performs in-place sorting to sort a list of objects. The sorting can be done using a Comparison<T> delegate or an IComparer<T> implementation.

1. Using Comparison<T> Delegate

A comparison delegate is used to provide order on objects that don’t have a natural ordering. If passed to a sort method, it allows precise control over the sort order of elements. We can implement the comparison delegate via anonymous methods, which allow code blocks to be passed as parameters instead of a separate method.

The following example sorts a list of Employee objects by their age using the specified Comparison<T> delegate.

Download  Run Code

 
Lambda expressions offer a more concise way of writing inline code blocks in C#. To compare the List of Employee objects by their age, we can do:

Download  Run Code

2. Implement IComparer<T>

Another approach is to provide a custom IComparer<T> implementation for sorting a list using the Sort() method. The idea is to implement the IComparer<T> interface in a separate class and pass that class’s instance to the Sort() method.

The implementing class needs to override the Compare() method, which takes two objects. The value returned by the Compare() method decides the relative order of the first object with respect to the second object in the sorted list. A negative, zero, and a positive value representing the first object is less than, equal to, or greater than the second object. This is demonstrated below:

Download  Run Code

3. Implement IComparable<T>

The IComparable<T> Interface imposes a natural ordering on the objects of each class that implements it. The implementing class needs to override the CompareTo() method, which compares the current object with the specified object. The value returned by the compareTo() method decides the relative order of the objects in the sorted list. A negative, zero, and a positive value representing the object is less than, equal to, or more than the specified object.

In the following code, the Employee class implements the IComparable<T> interface and override its CompareTo() method. The List of Employee objects is then sorted using the no-arg Sort() method.

Download  Run Code

4. Using LINQ OrderBy() method

The List Sort() method sorts the list in-place. To create a new sorted copy of the list, we can use LINQ’s OrderBy() method. This creates a new list with the elements of the original list sorted according to a key. The following code example demonstrates its usage:

Download  Run Code

Using LINQ Query Expressions:

Download  Run Code

That’s all about sorting a list of objects in C#.