Linq选择记录范围

时间:2011-03-06 23:09:26

标签: linq sql-server-2008 pagination paging

    var q = (from Comments in db.tblBlogComments where Comments.blogID == this.ID orderby Comments.date descending select new {
        Comments.userID, Comments.comment, Comments.date
    });

这会返回所有关联的记录,我最好如何选择记录#10到#20,这样我才不会加载任何冗余数据?

3 个答案:

答案 0 :(得分:4)

怎么样:

var q = (
from Comments in db.tblBlogComments 
where Comments.blogID == this.ID 
orderby Comments.date descending 
select new { Comments.userID, Comments.comment, Comments.date }).Skip(10).Take(10);

答案 1 :(得分:2)

您可以在结果集上使用.Skip().Take()方法。例如:

var q = (from Comments in db.tblBlogComments where Comments.blogID == this.ID orderby Comments.date descending select new {
    Comments.userID, Comments.comment, Comments.date
});

然后使用:

int pageSize = 10;
int page = 3;
var currentPage = q.Skip((currentPage - 1) * pageSize).Take(pageSize);

然后

foreach(var item in currentPage)
{
    ...
}

由于Linq使用延迟执行,将在foreach循环期间创建并执行实际查询。所以SQL查询只返回当前页面的记录。

修改:More information about this subject

答案 2 :(得分:0)

int start = 10;
int end = 20;
var q = (from Comments in db.tblBlogComments 
            where Comments.blogID == this.ID 
            orderby Comments.date descending 
            select new {
                          Comments.userID, 
                          Comments.comment, 
                          Comments.date
                       }).Skip(start).Take(end - start);

我不确定Skip是否转换为在数据库中执行的SQL,因此效率可能不高。

相关问题