Linq ThenBy and ThenByDescending Method

LINQ ThenBy and ThenByDescending Method in C# with Examples

In this article, I am going to discuss the LINQ ThenBy and ThenByDescending Method in C# with examples. Please read our previous article before proceeding to this article where we discussed the OrderByDescending method in C# with some examples. Here, in this article, we are going to discuss the following pointers related to the LINQ  ThenBy and ThenByDescending Method in C#.

  1. Why we need the ThenBy and ThenByDescending Method in C#?
  2. What are the ThenBy and ThenByDescending Method in C#?
  3. Example of Linq ThenBy and ThenByDescending Method using both Method and Query Syntax.
  4. How to use the ThenBy and ThenByDescending along with the Filtering method?
Why we need the LINQ ThenBy and ThenByDescending Method in C#?

The LINQ OrderBy or OrderByDescending method works fine when you want to sort the data based on a single value or a single expression. But if you want to sort the data based on multiple values or multiple expressions then you need to use the LINQ ThenBy and ThenByDescending Method along with OrderBy or OrderByDescending Method.

What are the Linq ThenBy and ThenByDescending Method in C#?

The Linq ThenBy Method in C# is used to sort the data in ascending order from the second level onwards. On the other hand, the  Linq ThenByDescending Method in C# is used to sort the data in descending order also from the second level onwards.

These two methods are used along with OrderBy or OrderByDescending method. You can use the ThenBy or ThenByDescending method more than once in the same LINQ query.

The OrderBy or OrderByDescending method are generally used for primary sorting. ThenBy or ThenByDescending are used for secondary sorting and so on. For example, first, sort the student by First Name and then sort the student by the Last Name.

Example:

We are going to use the following Student class in order to understand the use of ThenBy and ThenByDescending method in C#.

using System.Collections.Generic;
namespace LINQDemo
{
    public class Student
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Branch { get; set; }

        public static List<Student> GetAllStudents()
        {
            List<Student> listStudents = new List<Student>()
            {
                new Student{ID= 101,FirstName = "Preety",LastName = "Tiwary",Branch = "CSE"},
                new Student{ID= 102,FirstName = "Preety",LastName = "Agrawal",Branch = "ETC"},
                new Student{ID= 103,FirstName = "Priyanka",LastName = "Dewangan",Branch = "ETC"},
                new Student{ID= 104,FirstName = "Hina",LastName = "Sharma",Branch = "ETC"},
                new Student{ID= 105,FirstName = "Anugrag",LastName = "Mohanty",Branch = "CSE"},
                new Student{ID= 106,FirstName = "Anurag",LastName = "Sharma",Branch = "CSE"},
                new Student{ID= 107,FirstName = "Pranaya",LastName = "Kumar",Branch = "CSE"},
                new Student{ID= 108,FirstName = "Manoj",LastName = "Kumar",Branch = "ETC"},
                new Student{ID= 109,FirstName = "Pranaya",LastName = "Rout",Branch = "ETC"},
                new Student{ID= 110,FirstName = "Saurav",LastName = "Rout",Branch = "CSE"}
            };

            return listStudents;
        }
    }
}
Example: Using Method Syntax:

First, we need to sort the student by First Name in ascending order and then we need to sort the student by the Last Name in ascending order.

using System;
using System.Linq;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Method Syntax
            var MS = Student.GetAllStudents()
                              .OrderBy(x => x.FirstName)
                              .ThenBy(y => y.LastName)
                              .ToList();
            
            foreach (var student in MS)
            {
                Console.WriteLine( "First Name :" + student.FirstName + ", Last Name : " + student.LastName);
            }

            Console.ReadKey();
        }
    }
}

Output:

LINQ ThenBy and ThenByDescending Method in C#

Example: Using Query Syntax:

We do not have any method called ThenBy and ThenByDescending in query syntax. So here we need to specify multiple values or expression in the order by clause separated by a comma as shown in the below example.

using System;
using System.Linq;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Query Syntax
            var QS = (from std in Student.GetAllStudents()
                      orderby std.FirstName, std.LastName
                      select std);

            foreach (var student in QS)
            {
                Console.WriteLine( "First Name :" + student.FirstName + ", Last Name : " + student.LastName);
            }

            Console.ReadKey();
        }
    }
}

It will give us the same output as Method Syntax.

Example:

First sort the data in ascending order based on Branch. Then sort the data in descending order based on First Name. Finally, sort the data on the ascending order based on the Last Name values.

using System;
using System.Linq;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using Method Syntax
            var MS = Student.GetAllStudents()
                     .OrderBy(x => x.Branch)
                     .ThenByDescending(y => y.FirstName)
                     .ThenBy(z => z.LastName)
                     .ToList();

            //Query Syntax
            var QS = (from std in Student.GetAllStudents()
                      orderby std.Branch ascending, 
                              std.FirstName descending, 
                              std.LastName
                      select std).ToList();

            foreach (var student in QS)
            {
                Console.WriteLine( "Barnch " + student.Branch+ ", First Name :" + student.FirstName + ", Last Name : " + student.LastName);
            }

            Console.ReadKey();
        }
    }
}

Output:

LINQ ThenBy and ThenByDescending Method

Example: Using ThenBy and ThenByDescending along with the Where Method:

Here first we need to fetch only the CSE branch students and then we need to sort the data as follows. First sort the data in ascending order based on First Name. Then sort the data in descending order based on the Last Name.

using System;
using System.Linq;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using Method Syntax
            var MS = Student.GetAllStudents()
                     .Where(std => std.Branch == "CSE")
                     .OrderBy(x => x.FirstName)
                     .ThenByDescending(y => y.LastName)
                     .ToList();

            //Query Syntax
            var QS = (from std in Student.GetAllStudents()
                      where std.Branch == "CSE"
                      orderby std.FirstName, 
                              std.LastName descending
                      select std).ToList();

            foreach (var student in QS)
            {
                Console.WriteLine( "Barnch " + student.Branch+ ", First Name :" + student.FirstName + ", Last Name : " + student.LastName);
            }

            Console.ReadKey();
        }
    }
}

Output:

ThenBy and ThenByDescending Method in LINQ

In the next article, I am going to discuss the LINQ Reverse Method in C# with examples. I hope this article gives you a very good understanding of how to use and when to use the ThenBy and ThenByDescending method in C#. I hope you enjoy this article.

Leave a Reply

Your email address will not be published. Required fields are marked *