The topics that we will discuss in this article are:
- OrderBy
- OrderByDescending
- ThenBy
- 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.
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.
- public List<Employee> GetEmployee () {
- List<Employee> EmployeeList = new List<Employee>() {
- new Employee() {
- EmployeeId = 901,
- Name = "Kingsman",
- Gender = "Male",
- Salary = 50000
- },
- new Employee() {
- EmployeeId = 830,
- Name = "Aiden Pearce",
- Gender = "Male",
- Salary = 70500.45
- },
- new Employee() {
- EmployeeId = 212,
- Name = "Lara Croft",
- Gender = "Female",
- Salary = 30000
- },
- new Employee() {
- EmployeeId = 101,
- Name = "Black Widow",
- Gender = "Female",
- Salary = 10000
- },
- };
- return EmployeeList;
- }
In the same solution, add a new project “OrderByOperator” that will look like this.
Create an instance of the Employee class in the Main method of the OrderByOperator and for that we can say Employee.
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.
Once the Reference Manager Window pops-up, expand Projects and select the solution “EmployeeLibrary” from the solution window.
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.
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.
As we know in this Employee class there is a method “GetEmployee()” that will provide us the list of Employees back.
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.
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.
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.
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.
Now all we need to do is loop through each Employee object in employeeOrderBy and for that we can use the foreach loop.
The following is the entire code snippet.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using EmployeeLibrary;
- namespace OrderByOperator {
- class Program {
- static void Main (string[] args) {
- Employee employee = new Employee();
- List<Employee> employeeList = employee.GetEmployee();
-
- #region OrderBy operator Before and After
- List<Employee> employeeBeforeOrderBy = employeeList;
- Console.WriteLine("Before OrderBy Operator");
- foreach (Employee emp in employeeBeforeOrderBy) {
- Console.WriteLine("Id - "+emp.EmployeeId+" Name - "
- +emp.Name+" Gender - "+emp.Gender
- +" Salary - "+emp.Salary);
- }
- Console.WriteLine();
- IOrderedEnumerable<Employee> employeeOrderBy = employeeList
- .OrderBy(x => x.EmployeeId);
- Console.WriteLine("After OrderBy Operator");
- foreach (Employee emp in employeeOrderBy) {
- Console.WriteLine("Id - "+emp.EmployeeId+" Name - "
- +emp.Name+" Gender - "+emp.Gender
- +" Salary - "+emp.Salary);
- }
- #endregion
- }
- }
- }
Run the application.
So, now the result is sorted in an ascending order.
We can do the same thing by writing a SQL like query.
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.
Use the foreach loop to loop through each Employee and display it on the console window.
The following is how to do the same using a query like SQL.
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.
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.
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.
We can do the same using a query like SQL.
Use a foreach loop to loop through each Employee and display it on the console window.
Run the application.
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.
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.
We can do the same using a query like SQL.
Use a foreach loop to loop through each Employee and display it on the console window.
Run the application.
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.