OrderByDescending
This sorts elements from high to low. It is an extension method found in the System.Linq
namespace. It receives a key selector Func
instance.
We pass OrderByDescending
a lambda expression that selects the key. The OrderBy
method actually means OrderByAscending
, as it sorts from low to high.
OrderByDescending
exampleHere, each Tuple
has 2 items of type int
. Next, we call OrderByDescending
and use a lambda expression that selects the Item1
property of each Tuple
instance.
Item1
value to the lowest Item1
value.using System; using System.Linq; // 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); }(6, 4) (3, 6) (0, 60)
OrderBy
exampleOrderBy
specifies how a collection should be ordered. It is an extension method. We can invoke OrderBy
on any collection that implements IEnumerable
.
Func
as the argument. On the right side of the lambda, we reverse each string
to get the sort key.IOrderedEnumerable
) consists of the 4 strings sorted by their characters considered in reverse order.using System; using System.Linq; // Input array. string[] array = { "the", "glass", "bead", "game" }; // Order alphabetically by reversed strings. var result = array.OrderBy(a => new string(a.ToCharArray().Reverse().ToArray())); // Display results. foreach (var item in result) { Console.WriteLine(item); }bead the game glass
OrderBy
and OrderByDescending
are often used by the C# compiler when it translates query expressions with the descending contextual keyword.
These 2 methods are sometimes useful. But most often they are used in the translation of query expressions with the orderby
and descending keywords.