[LINQ Operators] ThenByDescending

The “OrderBy“, “OrderByDescending“, “ThenBy“, and “ThenByDescending” operators order a sequence according to one or more keys. You can provide the custom comparer “IComparer<K>”.

 

1. Sample Data Object

To test examples, you need to include the <data classes> in your project.

 

2. “ThenByDescending” operator

  • Deferred operator
  • Purpose: Ordering

 

3. Prototypes

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

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

The “ThenByDescending()” performs a subsequent ordering of the elements in descending order.

 

4. Example 1 (Standard Operator)

var emps = Employee.GetEmployees();

var newEmps
  = emps.OrderBy(e => e.Name.Length).ThenByDescending(e => e.Id);

foreach (var e in newEmps)
{
  Console.WriteLine($"{e.Id}: {e.Name}");
}

 

5. Example 2 (Query Expression)

var emps = Employee.GetEmployees();

var newEmps
  = (from e in emps
     orderby e.Name.Length ascending, e.Id descending
     select e);

foreach (var e in newEmps)
{
  Console.WriteLine($"{e.Id}: {e.Name}");
}

 

6. Example 3 (Standard Operator): with a custom comparer

public class MyIdComparer : IComparer*lt;int>
{
  // ordered by Id
  public int Compare(int id1, int id2)
  {
    return id1.CompareTo(id2);
  }
}

You can pass the custom comparer to the operator.

var emps = Employee.GetEmployees();
var comp = new MyIdComparer();

var newEmps
  = emps.OrderBy(e => e.Name.Length).ThenByDescending((e=>e.Id), comp);

foreach (var in newEmps)
{
  Console.WriteLine($"{e.Id}: {e.Name}");
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s