C# orderby Query KeywordUse the orderby keyword in a query expression. Include System.Linq.
dot net perls
Orderby. 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.
C# method notes. 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.
First example. 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.
Info The identifier "element" is entirely arbitrary, and it is just declared in each individual query.
Ascending We see that the first query expression and the second query expression both perform an ascending sort.
Tip 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.
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); } } }
result0 2 3 5 result1 2 3 5 result2 5 3 2
Compiler. 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 The extension method calls are why the System.Linq namespace is required.
Info The extensions OrderBy, and OrderByDescending are used when the C# compiler parses query expressions.
OrderBy, OrderByDescending
A summary. We used query expressions with ascending and descending, resulting in 3 sorted and enumerable collections. We examined the query syntax intermediate form.
© 2007-2021 sam allen. see site info on the changelog