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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System.Collections.Generic;
using System.Linq;
namespace ChangeOrder2
{
public interface Name
{
string First { get; }
string Middle { get; }
string Last { get; }
}
public static class ThenBy1
{
// Return the provided list of names, ordered by Last, then
// First, then Middle
public static IEnumerable<Name> SortNames(IEnumerable<Name> names)
{
// Uncomment:
// return names.???();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content