C# 选择前 10 条记录,然后选择下 10 条,使用 Linq 进行分页
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9718117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting first 10 records, then next 10, paging using Linq
提问by den den
How select first 10 records, Then the next 10, Then the next 10, and so long as the array will not end.
如何选择前10条记录,然后是下10条,然后是下10条,只要数组不会结束。
Phrases = bannersPhrases.Select(x=>x.Phrase).Take(10).ToArray()
How get the next 10 records?
如何获取接下来的 10 条记录?
采纳答案by moribvndvs
var total = bannersPhrases.Select(p => p.Phrase).Count();
var pageSize = 10; // set your page size, which is number of records per page
var page = 1; // set current page number, must be >= 1 (ideally this value will be passed to this logic/function from outside)
var skip = pageSize * (page-1);
var canPage = skip < total;
if (!canPage) // do what you wish if you can page no further
return;
Phrases = bannersPhrases.Select(p => p.Phrase)
.Skip(skip)
.Take(pageSize)
.ToArray();
回答by Tsabo
You can use .Skip().This will return the next 10 items:
您可以使用.Skip(). 这将返回接下来的 10 个项目:
Phrases = bannersPhrases.Select(x=>x.Phrase).Skip(10).Take(10).ToArray()
回答by oleksii
回答by Martin Liversage
If you are doing paging and you just want to skip to a particular page you can use Skipand Takeas described in some of the other answers. However, if you want group the entire sequence into chunks of a particular size you can use GroupByinstead. Here is a small example:
如果您正在进行分页并且只想跳到可以使用的特定页面,Skip并且Take如其他一些答案中所述。但是,如果您想将整个序列分组为特定大小的块,则可以GroupBy改用。这是一个小例子:
var groupSize = 4;
// The characters 'a' - 'z'.
var source = Enumerable.Range(0, 26).Select(i => (Char) ('a' + i));
var groups = source
.Select((x, i) => new { Item = x, Index = i })
.GroupBy(x => x.Index/groupSize, x => x.Item);
foreach (var group in groups)
Console.WriteLine("{0}: {1}", group.Key, String.Join(", ", group));
The output is:
输出是:
0: a, b, c, d 1: e, f, g, h 2: i, j, k, l 3: m, n, o, p 4: q, r, s, t 5: u, v, w, x 6: y, z

