c# - 如何从 IQueryable 获取计数

标签 c# asp.net linq iqueryable

我正在我的 GridView 中实现分页。来自 this文章,我需要两种方法:

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);
} 

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

如何从第一个方法 BindEmployees 中获取第二个方法 GetEmployeeCount 的值?我的意思是不重复逻辑(查询)?

最佳答案

一个选项是:

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);
}

另一种选择是将查询传递给分页函数。

关于c# - 如何从 IQueryable 获取计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5449863/

相关文章:

c# - 两台不同的 Azure 服务器上的相同代码,但其中一台存在路由问题?

asp.net - 如何使用文化来更改日期时间格式

c# - CollectionViewSource 在 XAML 中不能是 DataBound 但在 CodeBehind 中可以吗?

c# - MaskedTextBox 中的 IP 地址?

c# - HttpResponseMessage 在使用 HttpClient 时缺少 header ,但 fiddler 找到了

c# - 如何获得浏览量最高的前5名产品?

.net - IEnumerable 为空?

c# - tabpage中的foreach控件

jquery - 在 css 中覆盖系统样式外观在 asp.net 中不起作用

c# - 获取以下实体之间的差异 Linq to Entities