使用 LINQ 对对象进行分页 [英] Paging with LINQ for objects

查看:29
本文介绍了使用 LINQ 对对象进行分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何在 LINQ 查询中实现分页?其实暂时如果能模仿sql TOP功能我就满足了.但是,我相信无论如何都会很快需要完整的分页支持.

How would you implement paging in a LINQ query? Actually for the time being, I would be satisfied if the sql TOP function could be imitated. However, I am sure that the need for full paging support comes up sooner later anyway.

var queryResult = from o in objects
                  where ...
                  select new
                      {
                         A = o.a,
                         B = o.b
                      }
                   ????????? TOP 10????????

推荐答案

您正在寻找 SkipTake 扩展方法.Skip 移过结果中的前 N ​​个元素,返回余数;Take 返回结果中的前 N ​​个元素,删除所有剩余元素.

You're looking for the Skip and Take extension methods. Skip moves past the first N elements in the result, returning the remainder; Take returns the first N elements in the result, dropping any remaining elements.

有关如何使用这些方法的详细信息,请参阅 MSDN:http://msdn.microsoft.com/en-us/library/bb386988.aspx

See MSDN for more information on how to use these methods: http://msdn.microsoft.com/en-us/library/bb386988.aspx

假设您已经考虑到 pageNumber 应该从 0 开始(按照评论中的建议每 1 减少)您可以这样做:

Assuming you are already taking into account that the pageNumber should start at 0 (decrease per 1 as suggested in the comments) You could do it like this:

int numberOfObjectsPerPage = 10;
var queryResultPage = queryResult
  .Skip(numberOfObjectsPerPage * pageNumber)
  .Take(numberOfObjectsPerPage);

否则,如果 pageNumber 是基于 1 的(如@Alvin 所建议的)

Otherwise if pageNumber is 1-based (as suggested by @Alvin)

int numberOfObjectsPerPage = 10;
var queryResultPage = queryResult
  .Skip(numberOfObjectsPerPage * (pageNumber - 1))
  .Take(numberOfObjectsPerPage);

这篇关于使用 LINQ 对对象进行分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆