O'Reilly logo

LINQ Pocket Reference by Joseph Albahari, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required