使用 LINQ to SQL 获得分页结果的最佳模式是什么?
我有以下场景:
假设我想按描述 搜索items 表。我可以轻松做到:
public IQueryable<Item> FindItemsByDescription(string description)
{
return from item in _dc.Items
where item.Description.Contains(description);
}
现在,对这个结果集进行分页的最佳方式是什么?
- 我是否应该在执行此操作之前执行计数 查询以找出结果集大小,然后根据我的需要限制此查询?我觉得这是要走的路。
- 我是否应该执行完整查询,从数组大小中获取计数并仅返回该数组的分页子集?我觉得如果结果集足够大,这将是一种巨大的时间浪费……或者 LINQ to SQL 是否在这里施展魔法?
是否有LINQ to SQL执行此操作的通用模式?
编辑:我必须澄清一件小事。我知道 Take 和 Skip 方法。但是,在使用 Take 和 Skip 之前,我应该如何获取查询将检索的结果的总数?
最佳答案
分页的模式非常简单。它涉及 Skip() 和 Take() 扩展方法的使用,如下所示:
public IQueryable<Item> FindItemsByDescription(string description, int pageIndex, int pageSize)
{
return from item in _dc.Items
where item.Description.
Contains(description).
Skip((pageIndex - 1) * pageSize).
Take(pageSize);
}
更新:要获取总计数,只需使用 Count() 方法:
int totalCount = from item in _dc.Items
where item.Description.
Contains(description).Count();
int numberOfPages = (int)(totalCount/pageSize);
根据您打算如何显示记录,您可以使用 numberOfPages 显示带有“Page X of Y”的导航栏......第 1 页,共 10 页,等等。
关于c# - 使用 LINQ to SQL 对搜索结果进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/793718/