How to Sort a List by a property in the object?

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.
C# Sort List Person by DateTime

Sort List Using OrderBy – Method 1

Namespace System.Linq.


var ascedingPersonList = personList.OrderBy(p => p.DateOfBirth).ToList();


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.


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:

Leave a Comment