LINQ To SQL: Order by operator

EmpDetails Table:

LinqTable.png


Code:


The following example uses where to sort Employees in ascending order by Name
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
LINQ
{
class Program
{
static void Main(string[] args)
{
DataClassesDataContext dc = new DataClassesDataContext();
IOrderedQueryable<EmpDetail> empQuery = (from emp in dc.EmpDetails
orderby emp.Name
select emp);
foreach (EmpDetail empDetail in empQuery)
{
Console.WriteLine("ID :{0}, Name :{1}, Location :{2}, Department :{3}", empDetail.ID, empDetail.Name, empDetail.Location, empDetail.Dept);
}
Console.ReadLine();
}
}
}

OrderBy.png


The following example uses where to sort Employees in descending order by Name


using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
LINQ
{
class Program
{
static void Main(string[] args)
{
DataClassesDataContext dc = new DataClassesDataContext();
IOrderedQueryable<EmpDetail> empQuery = (from emp in dc.EmpDetails
orderby emp.Name descending
select emp);
foreach (EmpDetail empDetail in empQuery)
{
Console.WriteLine("ID :{0}, Name :{1}, Location :{2}, Department :{3}", empDetail.ID, empDetail.Name, empDetail.Location, empDetail.Dept);
}
Console.ReadLine();
}
}
}

Orderby2.png


DataClassesDataContext dc = new DataClassesDataContext();
IOrderedQueryable<EmpDetail> empQuery = (from emp in dc.EmpDetails
                                         where emp.Dept=="MOSS"
                                         orderby emp.Name descending
                                         select emp);
foreach (EmpDetail empDetail in empQuery)
{
Console.WriteLine("ID :{0}, Name :{1}, Location :{2}, Department :{3}", empDetail.ID, empDetail.Name, empDetail.Location, empDetail.Dept);
}
Console.ReadLine();
Orderby3.png

Ebook Download
View all
Learn
View all