Linq selecting range of records

前端 未结 3 1357
隐瞒了意图╮
隐瞒了意图╮ 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:32
    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);
    

    I'm not sure if Skip translates to SQL executed in the database, so this might be not so efficient.

    0 讨论(0)
  • 2020-12-12 01:42

    How about:

    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);
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题