ThenBy Method

public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector)
public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey>? comparer)

Description

Corresponds to the ThenBy method in LINQ.

Sorts the elements of a sequence in ascending order by using a specified comparer.

This method performs a stable sort using the default comparer.

Parameters

Name Type Description
source IOrderedEnumerable<TSource> An IOrderedEnumerable<TSource> to sort.
keySelector Func<TSource, TKey> A function to extract a key from each element.
comparer IComparer<TKey>? An IComparer<TKey> to compare keys, or null to use the default comparer.

Return Value

An IOrderedEnumerable<TSource> whose elements are sorted according to a key.

Remarks

The ThenBy method is used to perform a secondary sort on a sequence that has already been sorted by a primary key. It continues the ordering established by a previous OrderBy or OrderByDescending operation.

If the source sequence is not already ordered, using ThenBy will result in an exception.

Example

Demonstrates how to use the ThenBy method to sort a collection of strings by length and then alphabetically.


using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main(string[] args)
    {
        List<string> words = new List<string> { "cherry", "apple", "banana", "apricot", "blueberry", "avocado" };

        // Sort by length first, then alphabetically
        var sortedWords = words
            .OrderBy(w => w.Length)
            .ThenBy(w => w); // Default alphabetical sort

        Console.WriteLine("Sorted words:");
        foreach (var word in sortedWords)
        {
            Console.WriteLine(word);
        }
    }
}

Output:


apple
banana
cherry
apricot
avocado
blueberry