LINQ Take() returns the same results over and over

前端 未结 2 1845
隐瞒了意图╮
隐瞒了意图╮ 2021-01-24 04:40

I want to page over some records but the Take() extension from LINQ isn\'t returning the result which I expected.

public IQueryable<         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-24 05:09

    The Take method returns the first N records (N being the parameter) or all of the records if the total is less than N. To implement paging use it in conjunction with Skip, specifying how many records to skip before taking the next page of results. You may also want to supply some total ordering to ensure that the query returns results in the same order each time.

    Note: I've assumed zero-based paging.

    private const int _pageSize = 20;
    
    public IQueryable GetPersonBetweenDates(DateTime start, DateTime end, int? page)
    {
         return dbcontext.Persons
                         .Where(x => x.RegisterDate >= start && x.RegisterDate <= end)
                         .OrderBy(x => x.LastName)
                         .ThenBy(x => x.FirstName)
                         .ThenBy(x => x.Id) // using unique id to force consistent total order
                         .Skip((page ?? 0) * _pageSize)
                         .Take(_pageSize);
    }
    

提交回复
热议问题