C# OrderBy

LINQ: language integrated query

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

Lambda expression syntax

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 LiteralLambda ExpressionFunc TypeReverse

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)
	{
	    Console.WriteLine(item);
	}
    }
}

Output

bead
the
game
glass

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

Discussion

Note

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.

OrderBy ClauseOrderByDescending

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

Summary

The C# programming language

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.

Foreach Loop ExamplesArray.Sort Examples

C#: LINQ