C# OrderBy Extension Method: Use Lambda to Sort

This C# program demonstrates the OrderBy extension method from System.Linq.


specifies how a collection should be ordered. It is an extension method. With the System.Linq namespace, we can invoke OrderBy on any collection that implements IEnumerable.


we declare a string array. Next we invoke OrderBy and pass a lambda expression that matches the signature of Func as the argument. On the right side of the lambda, after =>, we reverse each string to get the sort key.String ArrayString LiteralFunc

We do this

by converting the string to an array with ToCharArray. Then we use the Reverse extension method. Next we convert that to a character array with ToArray. And finally we convert to a new string with the string constructor.ToCharArrayReverseToArrayString Constructor

Info: 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


The OrderBy method is used by the C# compiler whenever you use the orderby contextual keyword in a query expression. Query expressions are translated into method chains that include functions such as OrderBy and OrderByDescending.orderbyOrderByDescending

Tip: In some program contexts query expressions are easier to read. This is particularly true if multiple transforms in LINQ are required.


We saw an example of the OrderBy extension method. By using OrderBy with other syntax forms such as lambda expressions and the foreach-loop, we gain another way to sort collections without directly calling the default Sort methods.

Typically: The performance of extension methods such as OrderBy is inferior to that of the built-in sort methods such as Array.Sort.

Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen,