Ordering

Method

Description

SQL equivalents

OrderBy, ThenBy

Sorts a sequence in ascending order

ORDER BY …

OrderByDescending, ThenByDescending

Sorts a sequence in descending order

ORDER BY …DESC

Reverse

Returns a sequence in reverse order

Exception thrown

Ordering operators return the same elements in a different order.

OrderBy, OrderByDescending, ThenBy, ThenByDescending

OrderBy, OrderByDescending arguments

Argument

Type

Input sequence

IEnumerable<TSource>

Key selector

TSource => Tkey

Return type = IOrderedEnumerable<TSource>

ThenBy, ThenByDescending arguments

Argument

Type

Input sequence

IOrderedEnumerable<TSource>

Key selector

TSource => Tkey

Comprehension syntax

orderby expression1 [descending]
	  [, expression2 [descending] ... ]

Overview

OrderBy returns a sorted version of the input sequence, using the keySelector expression to make comparisons. The following query emits a sequence of names in alphabetical order:

	IEnumerable<string> query = names.OrderBy (s=> s);

The following sorts names by length:

	IEnumerable<string> query =
	  names.OrderBy (s => s.Length);

	// Result: { "Jay", "Tom", "Mary", "Dick", "Harry" };

The relative order of elements with the same sorting key (in this case, Jay/Tom and Mary/Dick) is indeterminate—unless you append a ThenBy operator:

	IEnumerable<string> query = names.OrderBy (s => s.Length)
	                                       . ThenBy (s => s);

	// Result: { "Jay", "Tom", "Dick", "Mary", "Harry" };

ThenBy reorders only elements that had the same sorting key in the preceding sort. You can chain any number of ...

Get LINQ Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.