Introduction
In order to sort a list of entities in a descending order with LINQ, we use the OrderByDescending method.
OrderByDescending
The OrderByDescending method allows you to sort a list of elements in a descending order.
Examples
Simple usage
List<int> list = new List<int> { 8000, 12, 900, 4, 1, 200};
List<int> values = list.OrderByDescending(l => l).ToList(); // { 8000, 900, 200, 12, 4, 1}
Note: we use the ToList method in order to avoid the following casting error:
Advanced usage
Besides using primitive types with the OrderByDescending method, we can also use reference types.
public class Person {
public string FullName { get; set; }
public int Age { get; set; }
}
List<Person> people = new List<Person> {
new Person { FullName = "Marc Thompson", Age = 40},
new Person { FullName = "Helen Walsh", Age = 53},
new Person { FullName = "Kelvin Terry", Age = 23},
new Person { FullName = "Carolyn Poole", Age = 17}
};
List<Person> values = people.OrderByDescending(l => l.Age).ToList(); // sorting people based on their age in a descending order
/*
Result:
Helen Walsh, 53
Marc Thompson, 40
Kelvin Terry, 23
Carolyn Poole, 17
*/
Namespace
To use the OrderByDescending method, you have to include this namespace:
using System.Linq;