TheDeveloperBlog.com


C# OrderBy Clause

Orderby. An orderby clause adds sorting to a query. It imposes a sorting algorithm to the expression's result. In the C# language, this clause is compiled to the OrderBy method. But often the clearest way to use the OrderBy method is with a clause.


Example. In this first section, we look at an example of the orderby clause. Please note how the "using System.Linq" directive is present at the top of the program. This is required because LINQ-specific features (extension methods) are used.

Here: The three query expressions use an orderby element, orderby element ascending, and orderby element descending syntax.

Also: The identifier "element" is entirely arbitrary, and it is just declared in each individual query.

C# program that uses orderby clause

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Input array.
	int[] array = { 2, 5, 3 };
	// Use orderby, orderby ascending, and orderby descending.
	var result0 = from element in array
		      orderby element
		      select element;

	var result1 = from element in array
		      orderby element ascending
		      select element;

	var result2 = from element in array
		      orderby element descending
		      select element;
	// Print results.
	Console.WriteLine("result0");
	foreach (var element in result0)
	{
	    Console.WriteLine(element);
	}
	Console.WriteLine("result1");
	foreach (var element in result1)
	{
	    Console.WriteLine(element);
	}
	Console.WriteLine("result2");
	foreach (var element in result2)
	{
	    Console.WriteLine(element);
	}
    }
}

Output

result0
2
3
5
result1
2
3
5
result2
5
3
2

We see that the first query expression and the second query expression both perform an ascending sort. The word ascending means "lowest to highest", like how a staircase ascends from the lowest step to the highest step.

And: The final query returns a descending sort, with the highest numbers going to the lowest numbers. This is the logical opposite.

Descending Keyword

Compiler. How are the orderby clauses in the query expressions compiled to the intermediate form? The C# specification describes a complex parsing mechanism that translates the query clauses into extension method calls.

Also, these specific extension method calls are why the System.Linq namespace is required. The extensions OrderBy, and OrderByDescending are used directly when the C# compiler parses query expressions.

OrderBy Extension MethodOrderByDescending

Summary. We demonstrated a program that applied three LINQ-based query expressions using the query syntax, resulting in three sorted and enumerable collections. We described the ascending and descending keywords.

And: We finally examined the nuts and bolts of query syntax in regards to the intermediate form.