Using C# LINQ - A Practical Overview


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


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
using System.Collections.Generic;
using System.Linq;
namespace ChangeOrder2
public interface Name
string First { get; }
string Middle { get; }
string Last { get; }
Create your playground on
This playground was created on, our hands-on, knowledge-sharing platform for developers.
Go to
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
Online Participants