Back
Close

Using C# LINQ - A Practical Overview

player_one
1637.7K views

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());

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
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io