LINQ Take()一遍又一遍地返回相同的结果 [英] LINQ Take() returns the same results over and over

查看:91
本文介绍了LINQ Take()一遍又一遍地返回相同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想翻页一些记录,但是LINQTake()扩展名没有返回我期望的结果.

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

public IQueryable<Person> GetPersonBetweenDates(DateTime start, DateTime end)
{
  return dbcontext.Persons.Where(x => x.RegisterDate >= start && x.RegisterDate <= end).Take(20);
}

再次运行此方法时,将得到相同的结果. Take()到底如何工作?

When I run this method again, I get the same result. How exactly does Take() work?

推荐答案

如果总数小于N,则Take方法返回前N条记录(N为参数)或所有记录.它与Skip结合使用,指定在获取下一页结果之前要跳过的记录数.您可能还需要提供一些总体排序,以确保查询每次都以相同的顺序返回结果.

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<Person> 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);
}

这篇关于LINQ Take()一遍又一遍地返回相同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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