C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Finally: We see that the Tuples are sorted from the highest Item1 value to the lowest Item1 value.
Info: A reverse sort (a descending sort) is performed. Using descending sorts is usually faster than using a separate reverse pass.
C# program that uses OrderByDescending
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)
Lambda: This matches the signature of Func as the argument. On the right side of the lambda, we reverse each string to get the sort key.
ArrayString LiteralInfo: We convert to an array with ToCharArray, Reverse the chars, convert to an array with ToArray, and create a string from that array.
ToCharArrayReverseToArrayString ConstructorFinally: The result (of type IOrderedEnumerable) consists of the 4 strings sorted by their characters considered in reverse order.
C# program that uses OrderBy extension method
using System;
using System.Linq;
class Program
{
static void Main()
{
// 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);
}
}
}
Output
bead
the
game
glass
Tip: Because query expressions do not require explicit delegate syntax (such as lambda expressions =>) they can be easier to read.
Quote: If an ordering clause specifies a descending direction indicator, an invocation of OrderByDescending or ThenByDescending is produced instead (The C# Programming Language).