There are two quick ways to sort List<T> based on the property of the complex C# object. For example, let’s sort this person list by DateOfBirth in ascending and descending order.
Sort List Using OrderBy – Method 1
Namespace System.Linq.
Ascending:
var ascedingPersonList = personList.OrderBy(p => p.DateOfBirth).ToList();
Descending
var descedingPersonList = personList.OrderByDescending(p => p.DateOfBirth).ToList();
Take into account that this creates a new list with all the items in memory. This may affect performance.
Sort(Comparison<T>) – Method 2
To prevent the creation of a new list it is better to use Sort(Comparison<T>) method. Namespace System.Collections.Generic.
Ascending:
personList.Sort((x, y) => x.DateOfBirth.CompareTo(y.DateOfBirth));
Descending (just swap x and y):
personList.Sort((x, y) => y.DateOfBirth.CompareTo(x.DateOfBirth));
You may also be interested in reading: