C# Enumerable OrderByDescending(IEnumerable, Func, IComparer)

Description

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

Syntax


public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(
  this IEnumerable<TSource> source,
  Func<TSource, TKey> keySelector,
  IComparer<TKey> comparer//w  w  w  . j  a va  2 s  . co  m
)

Parameters

  • TSource - The type of the elements of source.
  • TKey - The type of the key returned by keySelector.
  • source - A sequence of values to order.
  • keySelector - A function to extract a key from an element.
  • comparer - An IComparer to compare keys.

Example

The following code example demonstrates how to use OrderByDescending to sort the elements of a sequence in descending order by using a transform function and a custom comparer.


//  w  w  w. j a  va  2 s  . c o  m
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
    List<decimal> decimals = new List<decimal> { 61.2m, 81.3m, 10.5m, 11.3m, 16.3m, 19.7m };

    IEnumerable<decimal> query =
        decimals.OrderByDescending(num =>
                                       num, new SpecialComparer());

    foreach (decimal num in query)
    {
        Console.WriteLine(num);
    }

  }
}
    
public class SpecialComparer : IComparer<decimal>
{
    public int Compare(decimal d1, decimal d2)
    {
        return Decimal.Compare(d1, d2);
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable