Saturday, 18 February 2017

LINQ Ordering (Sorting) Operators: ThenBy, ThenByDescending and Reverse in C#

In the previous tutorial, I explained OrderBy and OrderByDescending in C# with examples. In this tutorial, we are going to learn ThenBy, ThenByDescending and Reverse operators in C#. LINQ sorting operators are used to arrange the collection data into ascending or descending order based on one or more attributes (fields).

Below are the five sorting operator.
1. OrderBy
2. OrderByDescending
3. ThenBy
4. ThenByDescending
5. Reverse

Related Articles

  1. Introduction to LINQ Standard Query Operators Vs SQL

ThenBy

OrderBy operator will sort values in ascending order. ThenBy is used after OrderBy to sort the collection data on another field in ascending order. LINQ will first sort the collection based on primary field which is specified by OrderBy and then resulted collection is sorted into ascending order again based on secondary field specified by ThenBy.

ThenByDescending

Just like ThenBy, ThenByDescending is used to sort data in descending order.

Reverse

Reverse operator simply sort collection data in reverse order.

Using ThenBy And ThenByDescending Method

To understand this, I have created a Employee class with 3 public properties and one static method which will return a list of all employees as shown below.

class Employee
{
  public int Id;
  public string Name;
  public int DeptId;

  public static List<Employee> GetAllEmployees()
  {
    Employee emp1 = new Employee { Id = 1, Name = "Yogesh", DeptId = 102 };
    Employee emp2 = new Employee { Id = 4, Name = "Rahul", DeptId = 101 };
    Employee emp3 = new Employee { Id = 3, Name = "Anil", DeptId = 102 };
    Employee emp4 = new Employee { Id = 2, Name = "Anil", DeptId = 101 };
    Employee emp5 = new Employee { Id = 5, Name = "Rahul", DeptId = 101 };

    List<Employee> empList = new List<Employee>();

    empList.Add(emp1);
    empList.Add(emp2);
    empList.Add(emp3);
    empList.Add(emp4);
    empList.Add(emp5);

    return empList;
  }
}

Now, let's print all employee's details before applying any kind of sorting.

static void Main(string[] args)
{
  List<Employee> obj = Employee.GetAllEmployees();

  Console.WriteLine("Before Sorting:");
  foreach (Employee e in obj)
  {
      Console.WriteLine(e.DeptId+"\t"+e.Name+"\t"+e.Id);
  }
  Console.ReadKey();
}

class Employee
{
  public int Id;
  public string Name;
  public int DeptId;

  public static List<Employee> GetAllEmployees()
  {
    Employee emp1 = new Employee { Id = 1, Name = "Yogesh", DeptId = 102 };
    Employee emp2 = new Employee { Id = 4, Name = "Rahul", DeptId = 101 };
    Employee emp3 = new Employee { Id = 3, Name = "Anil", DeptId = 102 };
    Employee emp4 = new Employee { Id = 2, Name = "Anil", DeptId = 101 };
    Employee emp5 = new Employee { Id = 5, Name = "Rahul", DeptId = 101 };

    List<Employee> empList = new List<Employee>();

    empList.Add(emp1);
    empList.Add(emp2);
    empList.Add(emp3);
    empList.Add(emp4);
    empList.Add(emp5);

    return empList;
  }
}

Output can be seen as below. First column is DeptId, 2nd is Name and 3rd is Id.

Before Sorting

Now, we will apply OrderBy on DeptId field to sort DeptId in ascending order and ThenBy on Name field to sort Name in ascending order.

static void Main(string[] args)
{
  IEnumerable<Employee> sortedResult = Employee.GetAllEmployees().OrderBy(x => x.DeptId).ThenBy(x => x.Name);

  Console.WriteLine("After Sorting DeptId and Name:");
  foreach (Employee e in sortedResult)
  {
      Console.WriteLine(e.DeptId + "\t" + e.Name + "\t" + e.Id);
  }
  Console.ReadKey();
}

As you can DeptId is sorted in ascending order and Name is also sorted in ascending.

After OrderBy and ThenBy

Now, we will apply OrderBy on DeptId field to sort DeptId in ascending order, ThenBy on Name field to sort Name in ascending order and ThenByDescending on Id field to sort Id in descending order.

static void Main(string[] args)
{
  IEnumerable<Employee> sortedResult = 
  Employee.GetAllEmployees().OrderBy(x => x.DeptId).ThenBy(x => x.Name).ThenByDescending(x => x.Id);

  Console.WriteLine("After Sorting All Columns:");
  foreach (Employee e in sortedResult)
  {
      Console.WriteLine(e.DeptId + "\t" + e.Name + "\t" + e.Id);
  }
  Console.ReadKey();
}

As you can se Id is sorted in descending order. 2nd and 3rd row got interchanged.

After OrderBy, ThenBy and ThenByDescending

Using ThenBy And ThenByDescending AS SQL Like Syntax

Now, same thing can be achieved using orderby in sql syntax. Here orderby keyword will sort DeptId field and Name field in ascending order by-default and Id field will be sorted in descending order using descending keyword.

static void Main(string[] args)
{
  IEnumerable<Employee> sortedResult = from e in Employee.GetAllEmployees()
                                                          orderby e.DeptId, e.Name, e.Id descending
                                                          select e;

  foreach (Employee e in sortedResult)
  {
      Console.WriteLine(e.DeptId + "\t" + e.Name + "\t" + e.Id);
  }
  Console.ReadKey();
}

Using Reverse Method

Now, we will use Reverse method to sort collection data in reverse order.

static void Main(string[] args)
{
  IEnumerable<Employee> ObjEmp = Employee.GetAllEmployees();
                                      
  Console.WriteLine("Before Reverse");
  foreach (Employee e in ObjEmp)
  {
      Console.WriteLine(e.DeptId + "\t" + e.Name + "\t" + e.Id);
  }

  Console.WriteLine();

  IEnumerable<Employee> ObjEmpReverse= ObjEmp.Reverse();

  Console.WriteLine("After Reverse");
  foreach (Employee e in ObjEmpReverse)
  {
      Console.WriteLine(e.DeptId + "\t" + e.Name + "\t" + e.Id);
  }

  Console.ReadKey();
}
Before and after Reverse
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON