sorting with linq using orderby operator


A common database operation performed frequently in database applications is sorting operation. The sorting operation sorts the elements in an ascending or descending order. The sorting operation can be done on one or more attributes. In LINQ sorting is done using orderby operator.

The below query retrieves the customer names from the customers table ordered by the customer name field. The return value of the orderby operator is an IOrderedQueryable. The IOrderedQueryable interface inherits from the IEnumerable interface.

SalesDBDataContext dataContext = new SalesDBDataContext();
IOrderedQueryable custQuery =
     from cust in dataContext.Customers
     orderby cust.Name
     select cust;
     foreach (Customer cusObj in custQuery)
       {
           Console.WriteLine("ID = {0}, Name = {1}", cusObj.CustomerId, cusObj.Name);
       }
     Console.ReadLine();



By default, the sorting operator performs sorting on ascending order on the field specified by orderby operator in a query. In some situations where we want to sort the elements in a descending order, we have to mention the keyword descending next to the field name. A simple Linq to sql query for sorting is shown below sorts the customers by customer name.

IOrderedQueryable custQuery =
     				from cust in dataContext.Customers
     				orderby cust.Name descending
     				select cust;

The below query sorts the customers by customer names first and then the results will be sorted again by the customer id in descending order.

IOrderedQueryable custQuery =
     from cust in dataContext.Customers
     orderby cust.Name,cust.CustomerId descending
     select cust;