Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

ThenBy(<keySelector>) method

ThenBy() specifies a secondary sort key that is used to further sort data that has already been sorted with a call to OrderBy().

IOrderedEnumerable<T>

ThenBy() is an interesting method. It is not an extension to IEnumerable<T>. Instead, it is a method of the IOrderedEnumerable<T> type, which is returned from OrderBy(), OrderByDescending(), ThenBy(), and ThenByDescending().

Since IOrderedEnumerable<T> implements the IEnumerable<T> interface, it can be thought of as an IEnumerable<T> with attached metadata that describes the order operations that have previously been performed on the sequence.

ThenBy() can be called any number of times, providing a new key on each subsequent call. Here is an example of ThenBy() usage:

List<string> strings = new List<string> { "first", "then", "and then", "finally" };
// Order by the last character, then by the first character
// Will contain { "and then", "then", "first", "finally" }
IEnumerable<string> result = strings.OrderBy(str => str.Last()).ThenBy(str => str.First());
Which of the following use correct syntax?

ThenBy() exercise

In the following exercise, try to order all the input names by Last. If any names have the same value for Last, then they should be ordered by First. If any have matching Last and First, then they should be ordered by Middle.

ThenBy Exercise
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content