
You want to order elements in your collection in the reverse sorted order based on a key. With the OrderByDescending extension method, we specify a key selector with a Func instance and the items are then sorted in reverse order, as shown in this example.
Func Type Extension Method
Let's get started by creating an array of Tuples. You can see that each Tuple has two items of type int. Next, we call OrderByDescending and use a lambda expression that selects the Item1 property of each Tuple instance. Finally, we see that the Tuples are sorted from the highest Item1 value to the lowest Item1 value.
Tuple Tips Lambda ExpressionThis C# program demonstrates the OrderByDescending extension method from System.Linq.
Program that uses OrderByDescending [C#]
using System;
using System.Linq;
class Program
{
static void Main()
{
// Create array of tuples.
Tuple<int, int>[] tuples = new Tuple<int, int>[3];
tuples[0] = new Tuple<int, int>(3, 6);
tuples[1] = new Tuple<int, int>(6, 4);
tuples[2] = new Tuple<int, int>(0, 60);
// Order by descending on Item1.
var result = tuples.OrderByDescending(a => a.Item1);
foreach (var item in result)
{
Console.WriteLine(item);
}
}
}
Output
(6, 4)
(3, 6)
(0, 60)Though OrderByDescending is a useful method in some situations, it is probably most often used by the C# compiler when it translates query expressions with the descending contextual keyword. Because query expressions do not require explicit delegate syntax (such as lambda expressions =>) they can be easier to read.
Descending KeywordWe demonstrated the OrderByDescending extension method found in the System.Linq namespace. This method requires a Func that selects a key. Further, we noted that OrderByDescending is commonly used in a way that is hidden—through the translation of query expressions with the orderby and descending keywords.
OrderBy Clause LINQ Examples