CSharp - LINQ ThenByDescending

Introduction

ThenByDescending operator is prototyped and behaves just like the ThenBy operator.

It orders in descending order.

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.

Prototypes

This operator has two prototypes we will cover.

The First ThenByDescending Prototype

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

This prototype of the operator orders in descending order.

ThenByDescending has a second prototype that looks like the following:

The Second ThenBy Descending Prototype

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

This prototype is the same as the first except it allows for a comparer object to be passed. If this
      version of the ThenByDescending operator is used, then it is not necessary that  K implement the
      IComparable interface.

Exceptions

ArgumentNullException is thrown if any arguments are null.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from w  w  w  .  jav a 2 s  . co m
{
    static void Main(string[] args)
    {
          string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
    
          IEnumerable<string> items = codeNames.OrderBy(s => s.Length).ThenByDescending(s => s);
    
          foreach (string item in items)
              Console.WriteLine(item);
    }
}

Result

The code above outputs where the names within each name length are sorted alphabetically in descending order.

Related Topics