OrderBy
Learn sorting with OrderBy and secondary sorting with ThenBy.
Sorting with OrderBy
The OrderBy method arranges the collection in ascending order. It takes a lambda that produces the sort key for each element. students.OrderBy(s => s.Age) sorts ascending by age.
For descending order use OrderByDescending. OrderBy is a stable sort: equal-keyed elements keep their original order. The result is an IOrderedEnumerable<T>, which can be followed by ThenBy.
Secondary sort with ThenBy
ThenBy adds a secondary sort key after an OrderBy. To sort students first by grade then by name: students.OrderBy(s => s.Grade).ThenBy(s => s.Name).
The secondary key only kicks in when the primary key is equal. ThenByDescending gives a descending secondary sort. A new OrderBy resets the previous sort, so for multi-key sorting you use ThenBy.
Exercise Sort numbers ascending
Sort the numbers array ascending with OrderBy and print each in a foreach loop.
Show example solution
Sort with numbers.OrderBy(n => n), loop with foreach, print with Console.WriteLine(n).
Example solution:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 7, 2, 9, 4 };
foreach (var n in numbers.OrderBy(n => n))
{
Console.WriteLine(n);
}
}
}
Test yourself
-
Which one is for secondary sorting?
- OrderBy
- OrderByDescending
- ThenBy
- Where
Show answer
Where — Correct. ThenBy adds a secondary sort after OrderBy.
-
Complete the sort call
var sorted = numbers.____(n => n);Show answer
var sorted = numbers.OrderBy(n => n); -
Match each method to its output
- OrderBy(n => n)
- 1, 2, 3
- OrderByDescending(n => n)
- 3, 2, 1
- ThenBy(s => s.Name)
- Secondary by name
- OrderBy(s => s.Age)
- Primary by age