Saturday, 11 February 2017

LINQ Ordering (Sorting) Operators: OrderBy and OrderByDescending in C#

In this article, we are going to learn LINQ ordering (sorting) operators in C# with examples. 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

In this tutorial, we are going to learn OrderBy and OrderByDescending operators only. Click here to read ThenBy, ThenByDescending and Reverse Operators.

OrderBy

OrderBy operator will sort values in ascending order. It sorts collection data in ascending order by default, here ascending keyword is optional.

OrderByDescending

OrderByDescending operator will sort values in descending order.

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.

Related Articles

  1. Introduction to LINQ Standard Query Operators Vs SQL

Using OrderBy 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 = "Rahul", DeptId = 102 };
        Employee emp2 = new Employee { Id = 4, Name = "Anil", DeptId = 101 };
        Employee emp3 = new Employee { Id = 3, Name = "Yogesh", DeptId = 102 };
        Employee emp4 = new Employee { Id = 2, Name = "Mary", DeptId = 101 };

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

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

        return empList;
    }
}

Let us print all employee's name before applying sorting.

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

        Console.WriteLine("Before Sorting:");
        foreach (Employee e in obj)
        {
            Console.WriteLine(e.Name);
        }
    }
}
class Employee
{
    public int Id;
    public string Name;
    public int DeptId;

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

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

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

        return empList;
    }
}
/*
OUTPUT
Before Sorting:
Rahul
Anil
Yogesh
Mary
*/

Now will be applying sorting using OrderBy on Name property.

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

    Console.WriteLine("Before Sorting:");
    foreach (Employee e in obj)
    {
        Console.WriteLine(e.Name);
    }

    Console.WriteLine();

    IEnumerable<Employee> sortedResult = Employee.GetAllEmployees().OrderBy(x => x.Name);

    Console.WriteLine("After Sorting:");
    foreach (Employee e in sortedResult)
    {
        Console.WriteLine(e.Name);
    }
    Console.ReadKey();
}
/*
OUTPUT
Before Sorting:
Rahul
Anil
Yogesh
Mary

After Sorting:
Anil
Mary
Rahul
Yogesh
*/

Using orderby As SQL Like Syntax

Now will use SQL like syntax.

static void Main(string[] args)
{
  IEnumerable<Employee> sortedResult = from emp in Employee.GetAllEmployees()
                                       orderby emp.Name // by default ascending order
                                       select emp;
  
  Console.WriteLine("After Sorting:");
  foreach (Employee e in sortedResult)
  {
      Console.WriteLine(e.Name);
  }
  Console.ReadKey();
}  
/*
OUTPUT
After Sorting:
Anil
Mary
Rahul
Yogesh
*/

Using OrderByDescending Method

Now will be applying sorting using OrderByDescending on Name property.

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

  Console.WriteLine("After Sorting:");
  foreach (Employee e in sortedResult)
  {
      Console.WriteLine(e.Name);
  }
  Console.ReadKey();
}  
/*
OUTPUT
After Sorting:
Yogesh
Rahul
Mary
Anil
*/

Using orderby with descending As SQL Like Syntax

Now will use SQL like syntax to sort them in descending order.

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

  Console.WriteLine("After Sorting:");
  foreach (Employee e in sortedResult)
  {
      Console.WriteLine(e.Name);
  }
  Console.ReadKey();
}  
/*
OUTPUT
After Sorting:
Yogesh
Rahul
Mary
Anil
*/

Sorting C# Array using OrderBy and OrderByDescending

string[] Subjects = { "Joomla", "C++", "VB", "Java", "ASP.Net", "C", "Perl" };

var sortedSubjects1 = from s in Subjects
                     orderby s
                     select s;
Console.WriteLine("After sorting in ascending order using sql like query");
foreach (string s in sortedSubjects1)
{
    Console.WriteLine(s);
}
/*
OUTPUT:
ASP.Net
C
C++
Java
Joomla
Perl
VB 
*/

var sortedSubjects2 = from s in Subjects
                     orderby s descending
                     select s;
Console.WriteLine("After sorting in descending order using sql like query");
foreach (string s in sortedSubjects2)
{
    Console.WriteLine(s);
}
/*
OUTPUT:
VB
Perl
Joomla
Java
C++
C
ASP.Net
*/

var sortedSubjects3 = Subjects.OrderBy(x => x);
Console.WriteLine("After sorting in ascending order using OrderBy method");
foreach (string s in sortedSubjects3)
{
    Console.WriteLine(s);
}
/*
OUTPUT:
ASP.Net
C
C++
Java
Joomla
Perl
VB 
*/

var sortedSubjects4 = Subjects.OrderByDescending(x => x);
Console.WriteLine("After sorting in descending order using OrderByDescending method");
foreach (string s in sortedSubjects4)
{
    Console.WriteLine(s);
}
Console.ReadKey();
/*
OUTPUT:
VB
Perl
Joomla
Java
C++
C
ASP.Net
*/

Sorting C# Array using OrderBy and OrderByDescending with Length Property

string[] Subjects = { "Joomla", "C++", "VB", "Java", "ASP.Net", "C", "Perl" };

var sortedSubjects1 = from s in Subjects
                      orderby s.Length  //you can use descending keyword after s.Length
                      select s;

Console.WriteLine("After Sorting");
foreach (string s in sortedSubjects1)
{
    Console.WriteLine(s);
}
/*
OUTPUT:
C
VB
C++
Java
Perl
Joomla
ASP.Net
*/

Console.WriteLine();

var sortedSubjects2 = Subjects.OrderByDescending(x => x.Length);

Console.WriteLine("After Sorting");
foreach (string s in sortedSubjects2)
{
    Console.WriteLine(s);
}
Console.ReadKey();
/*
OUTPUT:
ASP.Net
Joomla
Perl
Java
C++
VB
C
*/
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