orderby in query
Learn orderby and ascending/descending in query syntax.
Sorting with orderby
orderby sorts the elements of the query. The default direction is ascending; the descending keyword reverses it. Example: from n in numbers orderby n descending select n.
Multiple keys are comma-separated: orderby a, b descending. It first sorts by a, then by b for ties. Each key takes its own direction: orderby a ascending, b descending is valid.
Multiple keys
orderby takes multiple keys separated by commas. It first sorts by the first key; ties are broken by the second. Each key can have its own direction. Example: orderby e.Department, e.Salary descending.
This sorts employees first by department (ascending), then by salary (descending). Within a department, the highest salary comes first. Multiple keys are common in reporting and grouped views.
Exercise Sort numbers descending
Sort the numbers array in descending order with orderby n descending. Iterate with foreach and print with Console.WriteLine(n).
Show example solution
Write from n in numbers orderby n descending select n;. Then loop with foreach (var n in query) { Console.WriteLine(n); }.
Example solution:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 3, 1, 4, 1, 5, 9, 2, 6 };
var query = from n in numbers
orderby n descending
select n;
foreach (var n in query)
{
Console.WriteLine(n);
}
}
}
Test yourself
-
What is the default orderby direction?
- Ascending
- Descending
- Random
- Reversed
Show answer
Ascending — Correct. orderby defaults to ascending.
-
Add descending
var query = from n in numbers orderby n ____ select n;Show answer
var query = from n in numbers orderby n descending select n; -
Match the sort expression to its meaning
- orderby n
- Sorts by single key
- orderby n descending
- Sorts descending
- orderby a, b
- Sorts by multiple keys
- orderby n ascending
- Sorts ascending (default)