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 ...
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.