CSharp - LINQ ThenBy


ThenBy operator sorts an input ordered sequence of type IOrderedEnumerable<T> based on a keySelector method.

ThenBy operator yields an ordered output sequence of type IOrderedEnumerable<T>.

Both the ThenBy and ThenByDescending operators accept a different type of input sequence than most LINQ to Objects deferred query operators.

They take an IOrderedEnumerable<T> as the input sequence.

OrderBy or OrderByDescending operator must be called first to create an IOrderedEnumerable, then you can call the ThenBy or ThenByDescending operators.

The sort performed by the ThenBy operator is stable.

Unlike OrderBy and OrderByDescending, ThenBy and ThenByDescending are stable sorts.


The ThenBy operator has two prototypes we will cover.

The First ThenBy Prototype

public static IOrderedEnumerable<T> ThenBy<T, K>(
        this IOrderedEnumerable<T> source,
        Func<T, K> keySelector)
        K : IComparable<K>;

In this prototype of the ThenBy operator accepts an ordered input sequence of type IOrderedEnumerable<T> along with a keySelector method delegate.

The keySelector method accepts an input element of type T and will return the field within the element that is to be used as the key value, of type K.

Types T and K may be the same or different types.

The value returned by the keySelector method must implement the IComparable interface.

The ThenBy operator will order the input sequence in ascending order based on those returned keys.

The Second ThenBy Prototype

public static IOrderedEnumerable<T> ThenBy<T, K>(
        this IOrderedEnumerable<T> source,
        Func<T, K> keySelector,
        IComparer<K> comparer);

This prototype accepts a comparer object and does not require that type K implement the IComparable interface.


ArgumentNullException is thrown if any arguments are null.


using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*www .  j a v a2 s.  co m*/
    static void Main(string[] args)
        string[] codeNames = {
            "Python", "Java", "Javascript", "Bash", "C++", "Oracle"};

        IEnumerable<string> items = codeNames.OrderBy(s => s.Length).ThenBy(s => s);

        foreach (string item in items)


This example first orders by the input element length.

It then orders by the element itself.

The result is that the names are presented in length order, smallest to largest (ascending), and then alphabetically by name, ascending.

Related Topics