C# Enumerable ThenByDescending(IOrderedEnumerable, Func, IComparer)

Description

Performs a subsequent ordering of the elements in a sequence in descending order by using a specified comparer.

Syntax


public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(
  this IOrderedEnumerable<TSource> source,
  Func<TSource, TKey> keySelector,
  IComparer<TKey> comparer/*from w ww  . j a  v a 2 s .com*/
)

Parameters

  • TSource - The type of the elements of source.
  • TKey - The type of the key returned by keySelector.
  • source - An IOrderedEnumerable that contains elements to sort.
  • keySelector - A function to extract a key from each element.
  • comparer - An IComparer to compare keys.

Example

The following code example demonstrates how to use ThenByDescending to perform a secondary ordering of the elements in a sequence in descending order by using a custom comparer.


/*w  w w.j  av  a2  s .  com*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
       string[] fruits = { "apPLe", "orange", "BAnana", "ORANGE", "apPLE" };

       IEnumerable<string> query = fruits.OrderBy(fruit => fruit.Length)
           .ThenByDescending(fruit => fruit, new CaseInsensitiveComparer());

       foreach (string fruit in query)
       {
           Console.WriteLine(fruit);
       }

  }
}
    
public class CaseInsensitiveComparer : IComparer<string>{
    public int Compare(string x, string y)
    {
        return string.Compare(x, y, true);
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable