Ordering Operators in LINQ

The topics that we will discuss in this article are:

  1. OrderBy
  2. OrderByDescending
  3. ThenBy
  4. ThenByDescending

OrderBy and OrderByDescending are used to sort data just by one expression.

ThenBy and ThenByDescending is used along with OrderBy and OrderByDescending to sort data by more than one expression.

Let's understand all these ordering operators using an example.

In Visual Studio, I have created a class library named “EmployeeLibrary”. In this class library I have a class “Employee” with four auto-implemented properties.

EmployeeLibrary

In the same class we have a method that returns a list of employees and inside this method we created four objects of employees and added them to a list collection object.

  1. public List<Employee> GetEmployee () {  
  2.    List<Employee> EmployeeList = new List<Employee>() {  
  3.       new Employee() {  
  4.          EmployeeId = 901,  
  5.          Name = "Kingsman",  
  6.          Gender = "Male",  
  7.          Salary = 50000  
  8.       },  
  9.       new Employee() {  
  10.          EmployeeId = 830,  
  11.          Name = "Aiden Pearce",  
  12.          Gender = "Male",  
  13.          Salary = 70500.45  
  14.       },  
  15.       new Employee() {  
  16.          EmployeeId = 212,  
  17.          Name = "Lara Croft",  
  18.          Gender = "Female",  
  19.          Salary = 30000  
  20.       },  
  21.       new Employee() {  
  22.          EmployeeId = 101,  
  23.          Name = "Black Widow",  
  24.          Gender = "Female",  
  25.          Salary = 10000  
  26.       },  
  27.    };  
  28.    return EmployeeList;  

In the same solution, add a new project “OrderByOperator” that will look like this.

OrderByOperator

Create an instance of the Employee class in the Main method of the OrderByOperator and for that we can say Employee.

Employee class

Look at the image above, when we type Employee we don't get any suggestions because if we want to use the Employee class library in our project then the first thing we need to do is add a reference of the class library to the project we are working on and for that all we need to so is:

Go to Solution Explorer then expand the OrderByOperator project then right-click on References then select Add reference.

Add reference

Once the Reference Manager Window pops-up, expand Projects and select the solution “EmployeeLibrary” from the solution window.

Reference Manager

Click Ok.

So, now we have a reference to the Employee class. But when we say:

Employee

We encounter the same problem. We don't get a suggestion.

Employee

The reason is that the Employee class is present in the EmployeeLibrary namespace and to use the Employee class, we need to first import the namespace.

EmployeeLibrary namespace

As we know in this Employee class there is a method “GetEmployee()” that will provide us the list of Employees back.

GetEmployee

The return type of this GetEmployee method is List<Employee>. That means we can store the returning data in an object of that type.

The next thing is to retrieve all the employee records and print them on the console window and for that we can use a foreach loop.

employee records

Run the application.

Run the application

Now let's see how to use the Ordering Operators.

1. OrderBy Operator

Let's say we want to sort the result based on EmployeeId and for that we can use the OrderBy operator.

The OrderBy operator sorts the result in an asceding order.
OrderBy operator

Look at the parameter this OrderBy function expects. It is expecting a key, based on which the records will be sorted and here we will use employee id as the key.

OrderBy function

Look at the return type of this function, it returns an IOrderedEnumerable of Employee back, meaning we can assign the returning data in that kind of object.

IOrderedEnumerable

Now all we need to do is loop through each Employee object in employeeOrderBy and for that we can use the foreach loop.

employeeOrderBy

The following is the entire code snippet.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using EmployeeLibrary; 

  5. namespace OrderByOperator {  
  6.    class Program {  
  7.       static void Main (string[] args) {  
  8.          Employee employee = new Employee();  
  9.          List<Employee> employeeList = employee.GetEmployee();  
  10.  
  11.          #region OrderBy operator Before and After  
  12.          List<Employee> employeeBeforeOrderBy = employeeList;  
  13.          Console.WriteLine("Before OrderBy Operator");  
  14.          foreach (Employee emp in employeeBeforeOrderBy) {  
  15.             Console.WriteLine("Id - "+emp.EmployeeId+" Name - "  
  16.             +emp.Name+" Gender - "+emp.Gender  
  17.             +" Salary - "+emp.Salary);  
  18.          }  
  19.          Console.WriteLine();  
  20.          IOrderedEnumerable<Employee> employeeOrderBy = employeeList  
  21.          .OrderBy(x => x.EmployeeId);  
  22.          Console.WriteLine("After OrderBy Operator");  
  23.          foreach (Employee emp in employeeOrderBy) {  
  24.             Console.WriteLine("Id - "+emp.EmployeeId+" Name - "  
  25.             +emp.Name+" Gender - "+emp.Gender  
  26.             +" Salary - "+emp.Salary);  
  27.          }  
  28.          #endregion  
  29.       }  
  30.    }  

Run the application.

Run
So, now the result is sorted in an ascending order.

We can do the same thing by writing a SQL like query.

SQL like query

output

2. OrderByDescending

If you want to sort the result in descending order, use OrderByDescending.

OrderByDescending is the same as the OrderBy operator. All we need to do is to invoke this function on employeeList and pass the lambda expression.

OrderByDescending

Use the foreach loop to loop through each Employee and display it on the console window.

foreach loop

The following is how to do the same using a query like SQL.

achieve

Just add the descending keyword after the employees.EmployeeId.

Use a foreach loop to loop through each Employee and display it on the console window.

Run the application.

application

So, we have seen how to sort the results using OrderBy and OrderByDescending. Now let's see how to sort them using ThenBy and ThenByDescending.

Create a new project in the same solution and provide the name “ThenByOperator”. In this project add a reference to the EmployeeLibrary and import the namespace.

ThenBy

To sort a collection based on two expressions, use the ThenBy operator. Using this function is pretty straight forward, all we need to do is invoke the ThenBy function on the OrderBy function and pass the second expression.

Let's say we want to sort the result based on EmployeeId and Name.

Pass the first condition in the OrderBy and second in the ThenBy.

ThenBy

So, what this OrderBy and ThenBy will do is, first EmployeeId will sort in ascending order and then Name in ascending order and finally the final result will be displayed.

Use a foreach loop to loop through each Employee and display it on the console window.

display

We can do the same using a query like SQL.

linkquery

Use a foreach loop to loop through each Employee and display it on the console window.

console window

Run the application.

run program

ThenByDescending

To sort a collection in descending order based on two expressions, use the ThenByDescending operator. Using this function is pretty straight forward, all we need to do is invoke ThenByDescending function on the OrderBy function or OrderByDescending function and pass the second expression.

OrderByDescending function

We have passed two expressions. The first expression will sort the Id in ascending order and the second expression will sort the name in descending order.

Use a foreach loop to loop through each Employee and display it on the console window.

first expression

We can do the same using a query like SQL.

use SQL like query

Use a foreach loop to loop through each Employee and display it on the console window.

Use foreach loop

Run the application.

through each Employees

The advantage of using the ThenBy and ThenByDescending is, we can call or invoke these functions more than 1 time.

I hope you like it. Thank you.