Home
Map
C#
orderby Keyword
This page was last reviewed on May 9, 2023.
Dot Net Perls
Orderby. 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.
Sort
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.
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.
Next 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.
descending
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
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.
Detail The extension method calls are why the System.Linq namespace is required.
Extension
Info The extensions OrderBy, and OrderByDescending are used when the C# compiler parses query expressions.
OrderByDescending
With query expressions, the foreach-statement evaluates the queries as we loop over them. The can be considered fully lazy in this way.
foreach
A summary. We used query expressions with ascending and descending, resulting in 3 sorted and enumerable collections. We examined the query syntax intermediate form.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 9, 2023 (simplify).
Home
Changes
© 2007-2024 Sam Allen.