OrderBy, OrderByDescending in LINQ

 

In SQL, if you want to order the result set based on some column we use the ORDER BY clause as shown below.

 

SELECT * FROM Employees ORDER BY name

 

The above query returns the result by ordering the name in ascending order. The default the order is ascending order. If we want order the result set in desending order use below query.

 

SELECT * FROM Employees ORDER BY name DESC

 

In LINQ also, we can order the result set based on our requirement.

 

SELECT * FROM Employees ORDER BY name

 

Equivalent of above query in LINQ is

 

DataClassesDataContext db = new DataClassesDataContext(); 

var emp = db.Employees.OrderBy(e => e.name);

 

The above code returns result set by ordering the name in ascending order by using the OrderBy method. In LINQ also, if we are not mentioning the order by default it takes ascending order.

 

If we want to order the result set by ordering the name in descending order use below code.

 

DataClassesDataContext db = new DataClassesDataContext(); 

var emp = db.Employees.OrderByDescending(e => e.name);

 

The above code returns the result set by ordering the name in descending order by using LINQ OrderByDescending() method.