This post will discuss how to sort a list of objects against the multiple fields in C#.

1. Using LINQ

To create a sorted copy of the list, we can use LINQ’s OrderBy() method. To compare objects against subsequent fields, call the ThenBy() method (or ThenByDescending).

For example, the following code sorts the employee’s list first by the name field and then by the age field, i.e., for employees having the same name, the employee’s age determines the ordering.

Download  Run Code

2. Using List<T>.Sort method (System.Collections.Generic)

The above LINQ solution creates a new sorted copy of the list. The suggested approach is to use List’s Sort() method to sort the list in-place. The sorting can be done using a Comparison<T> delegate or an IComparer<T>/IComparable<T> implementation.

1. We can use a comparison delegate 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. A comparison delegate can be implemented using lambda expressions. To compare the List of Employee objects first by name and then by age, we can do:

Download  Run Code

 
2. Another approach is to provide the 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, override its Compare() method, and pass that class’s instance to the Sort() method. This is the preferred approach to lambda expressions when you have several fields to compare.

Download  Run Code

 
3. The IComparable<T> interface imposes a natural ordering on the objects of each class that implements it. 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

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