Ordering
Method | Description | SQL equivalents |
|---|---|---|
| Sorts a sequence in ascending order | |
| Sorts a sequence in descending order | |
| 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 | |
Key selector | |
Return type =
IOrderedEnumerable<TSource>
ThenBy, ThenByDescending arguments
Argument | Type |
|---|---|
Input sequence | |
Key selector | |
Comprehension syntax
orderbyexpression1[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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access