ThenBy
This operator always followed by orderby, means we always use it after using ordeby operator. If we use orderby and ThenBy together then first items will be sorted as per orderby given condition and resultant output sequence will be sorted by ThenBy condition.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQExample { class Program { static void Main(string[] args) { Employee[] Employees = { new Employee { Name = "Ramesh", salary = 500 }, new Employee { Name = "Suresh", salary = 100 }, new Employee { Name = "Yogesh", salary = 150 }, new Employee { Name = "Harish", salary = 500 }, new Employee { Name = "Vijay", salary = 100 } }; //sort elements as only by ordeby condition IEnumerable<Employee> query1 = Employees.OrderBy(X => X.salary); //sort elements as only by ordeby and thenby condition IEnumerable<Employee> query2 = Employees.OrderBy(X => X.salary).ThenBy(x=>x.Name); foreach (var Employee in query1) { Console.WriteLine("Employee Name="+Employee.Name+" Salary="+Employee.salary); } Console.WriteLine("----------------------------------------------------------------------"); Console.WriteLine("Now Elements first sorted by salary after it by name"); Console.WriteLine(); //Sorted in Salary and Name foreach (var Employee in query2) { Console.WriteLine("Employee Name=" + Employee.Name + " Salary=" + Employee.salary); } Console.ReadLine(); } } public class Employee { public string Name; public int salary; } }
We can also use ThenByDescending by writing following query
IEnumerable<Employee> query2 = Employees.OrderBy(X => X.salary).ThenByDescending(x => x.Name);