Ordering with OrderBy and OrderByDescending

In LINQ, the OrderBy and OrderByDescending methods are used to sort collections in ascending or descending order. These methods allow you to sort elements based on a key or a set of keys.

Sorting is often a critical operation when working with collections of data that need to be presented in a specific order.

OrderBy

The OrderBy method sorts a collection in ascending order based on a specified key.

Example

Let’s say you have a collection of Employee objects, and you want to sort them by their Salary in ascending order:

var sortedEmployees = employees.OrderBy(e => e.Salary);

How it works

  • OrderBy requires a key selector—a function that extracts the key by which the elements are sorted.
  • It returns an IOrderedEnumerable<T>, which represents a sequence that has been sorted and allows for further ordering.

Key Points

  • OrderBy sorts elements in ascending order.
  • It returns an IOrderedEnumerable<T>, which can be further refined with additional sorting methods like ThenBy.

OrderByDecending

The OrderByDescending method is similar to OrderBy, except it sorts elements in descending order.

Example

var sortedEmployeesDescending = employees.OrderByDescending(e => e.Salary);

How it works

  • Just like OrderBy, OrderByDescending takes a key selector and sorts elements based on that key.
  • It returns an IOrderedEnumerable<T>, which allows for further sorting or additional operations.

ThenBy for Secondary Sorting

After applying OrderBy or OrderByDescending, you can use the ThenBy method to specify a secondary sort key. This is useful when you need to sort by more than one property.

Example Secondary Sorting with ThenBy

var sortedEmployees = employees
    .OrderBy(e => e.Salary)
    .ThenBy(e => e.Name);

How it works

  • The collection is first sorted by Salary in ascending order.
  • For employees with the same Salary, the ThenBy method sorts them by Name in ascending order.
var sortedEmployees = employees
    .OrderBy(e => e.Salary)
    .ThenByDescending(e => e.Name);

Here, the employees are still sorted by Salary in ascending order, but for employees with the same Salary, they are sorted by Name in descending order.

IOrderedEnumerable<T>

Both OrderBy and OrderByDescending return an IOrderedEnumerable<T>, which is different from a regular IEnumerable<T> because it maintains the order of elements.

  • IOrderedEnumerable<T> allows you to chain additional ordering operations like ThenBy or ThenByDescending.
  • It is a specialized type that keeps track of the sorting rules applied to the sequence.
IOrderedEnumerable<Employee> sortedEmployees = employees.OrderBy(e => e.Salary);

It's a tiny callout - not really too consequential - but you'll see examples of this as you go through LINQ methods - sometimes they return IEnumerable<T> and sometimes they return other things more specialized for their task.