Friday, June 15, 2012

LINQ to SQL - Select Top N Rows


Before writing a LINQ to SQL query, we first need to create a DataContext using the LINQ to SQL Classes template, to know more on how to create the DataContext refer to the post LINQ to SQL Sample

Once the DataContext is created we can query the Object model using LINQ queries, let us consider the Employee table which has the following structure.


The below code will fetch all the rows from the Employee Table

EmployeeClassesDataContext dbContext = newEmployeeClassesDataContext();

var emp = from employees in dbContext.Employees 
          select employees;

grdEmployees.DataSource = emp;
grdEmployees.DataBind();


Now we will select only the Top 10 rows returned using the following LINQ query

EmployeeClassesDataContext dbContext = newEmployeeClassesDataContext();

var emp = (from e in dbContext.Employees
          select new { e.ID, e.Name, e.Phone }).Take(10);

grdEmployees.DataSource = emp;
grdEmployees.DataBind();

That’s it, Adding Take(n), filters the results and returns only the top n rows from the query.



Search Flipkart Products:
Flipkart.com

No comments: