[LINQ Operators] OrderByDescending

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. “OrderByDescending” operator

  • Deferred operator
  • Purpose: Ordering

 

3. Prototypes

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

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

The “OrderByDescending()” operator sorts the elements in descending order. Except that, it works the same ways as the “OrderBy()” operator works.

If you want to specify additional sort criteria, “ThenBy()” or “ThenByDescending()” operator should be used. If you use “OrderBy()” or “OrderByDescending()” again, the previous sort criteria will be ignored.

 

4. Example 1 (Standard Operator)

var emps = Employee.GetEmployees();

var newEmps = emps.OrderByDescending(e => e.Name);

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

 

5. Example 2 (Standard Operator): two “OrderByDescending” operators

var emps = Employee.GetEmployees();

// will be ordered only by ID
var newEmps
  = emps.OrderByDescending(e => e.Name).OrderByDescending(e => e.Id);

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

 

6. Example 3 (Query Expression)

var emps = Employee.GetEmployees();

var newEmps
  = (from e in emps
     orderby e.Name descending
     select e);

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

 

7. Example 4 (Standard Operator): with a custom comparer

public class MyEmployeerComparer : IComparer<string>
{
  // ordered by the length of the name
  public int Compare(string s1, string s2)
  {
    if (s1.Length < s2.Length)
      return -1;
    else if (s1.Length > s2.Length)
      return 1;
    else
      return 0;
  }
}

 

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

var newEmps = emps.OrderByDescending((e=>e.Name), comp);

foreach (var e 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