In C# an orderby
clause adds sorting to a query. It imposes a sorting algorithm to the expression's result. It can be placed within a query that also does other things.
In the C# language, the "orderby
" clause is compiled to the OrderBy
method. Often the clearest way to use the LINQ OrderBy
method is with a clause.
The "using System.Linq
" directive is present at the top. The 3 query expressions use an orderby
element, orderby
element ascending, and orderby
element descending syntax.
using System; using System.Linq; // 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); }result0 2 3 5 result1 2 3 5 result2 5 3 2
How are the orderby
clauses in the expressions compiled to the intermediate form? The C# specification describes how the query clauses are translated into extension method calls.
System.Linq
namespace is required.OrderBy
, and OrderByDescending
are used when the C# compiler parses query expressions.With query expressions, the foreach
-statement evaluates the queries as we loop over them. The can be considered fully lazy in this way.
We used query expressions with ascending and descending, resulting in 3 sorted and enumerable collections. We examined the query syntax intermediate form.