C# OrderBy Extension Method

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

OrderBy specifies how a collection should be ordered.

It is an extension method. With the System.Linq namespace in the C# language, we can invoke OrderBy on any collection that implements IEnumerable.



Example. First 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

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)



Info: The result (of type IOrderedEnumerable) consists of the four strings sorted by their characters considered in reverse order.


Discussion. 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.



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


Summary. 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.