This post will discuss how to sort an array of objects by a specific field in C#.

1. Using Enumerable.OrderBy Method

For out-of-place sorting of an array of objects, use the Enumerable.OrderBy() method by LINQ. It sorts the elements of a sequence in ascending order according to a key. For example, the following code sorts an array of Person objects by the age field:

Download  Run Code

Output:

[y, 21]
[z, 24]
[x, 27]
[z, 30]

 
This method can be used with .NET 3.5 and above. To sort in descending order instead, use the Enumerable.OrderByDescending method from LINQ.

Download  Run Code

Output:

[z, 30]
[x, 27]
[z, 24]
[y, 21]

 
To compare objects against multiple fields, call the ThenBy() or ThenByDescending() method. For instance, the following example sorts an array of objects by the name field. For two objects having the same name, the ordering is decided by their age.

Download  Run Code

Output:

[y, 21]
[z, 24]
[x, 27]
[z, 30]

2. Using Array.Sort method

To sort the array in-place, you can use the Array.Sort method, which will perform sorting using a delegate of type Comparison<T> or an instance of IComparer<T>/IComparable<T>.

For example, the following code uses a comparison delegate to provide precise control over the sort order of elements. The solution uses a lambda expression to compare an array of Person objects first by the name field, followed by the age field.

Download  Run Code

Output:

[y, 21]
[z, 24]
[x, 27]
[z, 30]

 
Alternatively, you can provide IComparable<T> implementation for sorting an array with the Array.Sort method. This can be done by having the class implement the IComparable<T> interface and override its CompareTo() method, as the following example illustrates.

Download  Run Code

Output:

[y, 21]
[z, 24]
[x, 27]
[z, 30]

That’s all about sorting an array of objects by a specific field in C#.