Linq selecting range of records

前端 未结 3 1370
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 01:22
    var q = (from Comments in db.tblBlogComments where Comments.blogID == this.ID orderby Comments.date descending select new {
        Comments.userID, Comments.com         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 01:57

    You can use the .Skip() and .Take() methods on your result set. Example:

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

    And then use:

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

    And then

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

    Since Linq uses deferred execution, the actual query will be created and executed during the foreach loop. So the SQL query will only return the records for the current page.

    Edit: More information about this subject

提交回复
热议问题