Ordering Operators in linq C#
These operators return same number of output elements as input elements in sorted form.
OrderBy
This operator sort input elements as per given key. For example we have a employee table which have a salary field now we want to get employee details in sorted form, means higher salary should come first and so on. Elements can be sort in ascending or descending.
Example
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 = "Sugar", salary = 500 }, new Employee { Name = "Egg", salary = 100 }, new Employee { Name = "Milk", salary = 150 }, new Employee { Name = "Flour", salary = 50 }, new Employee { Name = "Butter", salary = 200 } }; //sort elements as per salary IEnumerable<Employee> query = Employees.OrderBy(X => X.salary); //sort elements as per salary--Descending IEnumerable<Employee> query1 = Employees.OrderByDescending((X => X.salary)); foreach (var Employee in query) { Console.WriteLine("Employee Name="+Employee.Name+" Salary="+Employee.salary); } Console.WriteLine(); //To get descending order output foreach (var Employee in query1) { Console.WriteLine("Employee Name=" + Employee.Name + " Salary=" + Employee.salary); } Console.ReadLine(); } } public class Employee { public string Name; public int salary; } }