C# Reference ยท LINQ
LINQ OrderBy() and ThenBy() methods
Reference for LINQ OrderBy, OrderByDescending, ThenBy and ThenByDescending: stable sorting, custom comparers, multiple keys and common mistakes.
OrderBy() returns a new sequence sorted by a key you select from each element. OrderByDescending() sorts from high to low. To break ties with a second, third or later key, chain ThenBy() and ThenByDescending().
Unlike List<T>.Sort(), LINQ sorting does not change the source and is stable: elements with equal keys keep their original relative order. The sort runs when you enumerate the result, and it must read the whole source before it can return the first element.
var sorted = people.OrderBy(p => p.Country).ThenByDescending(p => p.Age);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector); public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey>? comparer); // OrderByDescending has the same overloads public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>( this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector); // ThenByDescending, and overloads with IComparer<TKey>
| Name | Description |
|---|---|
keySelector |
Extracts the sort key from an element. It runs once per element. |
comparer |
Optional. null or omitted means Comparer<TKey>.Default. |
Returns: an IOrderedEnumerable<TSource>. ThenBy() is defined only on that type, so you cannot start a chain with it.
Errors: ArgumentNullException for a null source or key selector. InvalidOperationException (while enumerating) if the key type is not comparable and no comparer is given.
Usage notes
- Stable sort. Equal keys keep source order, which
List<T>.Sort()does not guarantee. - Chain with
ThenBy(), not a secondOrderBy(). A secondOrderBy()starts a fresh sort and the earlier key only decides ties by accident of stability. - Strings use the default culture comparer. In this runner globalization is invariant, but on other machines the order can differ. Pass
StringComparer.Ordinal(orOrdinalIgnoreCase) for predictable results. - Complexity: O(n log n) time, O(n) extra memory. If you only need the first few items,
OrderBy(...).Take(k)is optimized in modern .NET, butMin()/MinBy()is cheaper for the single smallest item. - Descending ints: do not negate the key (
-x) for the full integer range:int.MinValueoverflows. UseOrderByDescending(). Order()andOrderDescending()(.NET 7+) sort elements by themselves without a key selector.- Sort in place instead with
List<T>.Sort()orArray.Sort()when you own the data and do not need a stable result. - Query syntax:
orderby p.Country, p.Age descending.