How to get the count from IQueryable

Homam picture Homam · Mar 27, 2011 · Viewed 40.5k times · Source

I am implementing paging in my GridView. From this article, I need two methods:

public IQueryable BindEmployees(int startRowIndex, int maximumRows)
{
    EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();
    var query = from emp in dbEmp.Employees
                join dept in dbEmp.Departments
                    on emp.DeptID equals dept.DeptID
                select new
                {
                    EmpID = emp.EmpID,
                    EmpName = emp.EmpName,
                    Age = emp.Age,
                    Address = emp.Address,
                    DeptName = dept.DepartmentName
                };

    return query.Skip(startRowIndex).Take(maximumRows);
} 

And

public int GetEmployeeCount()
{
    // How can I not repeat the logic above to get the count?
}

How can I get the value of the second method GetEmployeeCount from the first method BindEmployees ? I mean without repeating the logic (the query)?

Answer

Marc Gravell picture Marc Gravell · Mar 27, 2011

One option would be:

public IQueryable BindEmployees(int startRowIndex, int maximumRows, out int count)
{
    EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();
    var query = from emp in dbEmp.Employees
                join dept in dbEmp.Departments
                    on emp.DeptID equals dept.DeptID
                select new
                {
                    EmpID = emp.EmpID,
                    EmpName = emp.EmpName,
                    Age = emp.Age,
                    Address = emp.Address,
                    DeptName = dept.DepartmentName
                };

    count = query.Count();
    return query.Skip(startRowIndex).Take(maximumRows);
}

The other option is to pass the query into the paging function.