CSharp - LINQ OrderByDescending

Introduction

OrderByDescending orders input sequence in descending order.

Prototypes

This operator has two prototypes we will cover.

The First OrderBy Descending Prototype

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

This prototype of the OrderByDescending operator sorts the input sequence in descending order.

The sorting performed by OrderByDescending is unstable.

The Second OrderBy Descending Prototype

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

This prototype accepts a comparer object.

This version of the OrderByDescending operator does not require that type K implement the IComparable interface.

Exceptions

ArgumentNullException is thrown if any arguments are null.

The following code will order the codeNames in descending order by their names.

Demo

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

Result

Related Topics