C# 如何使用 Linq 对每 N 行进行分组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/860305/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:34:31  来源:igfitidea点击:

How to use Linq to group every N number of rows

c#linqgroup-by

提问by RBear

I cannot find a way to make this work and hoping someone has an idea. A simplified example would be having a list of say integers 1-100, i want to group every 3 rows so the result would be 1,2,3 in first group then 4,5,6 in next group etc. I know how to get every nth record but what I need is all the records so I can then aggregate them, using first, last, sum, max, etc.

我找不到使这项工作的方法,并希望有人有想法。一个简化的例子是有一个整数 1-100 的列表,我想每 3 行分组,所以结果将是第一组中的 1,2,3 然后下一组中的 4,5,6 等等。我知道如何获取每第 n 条记录,但我需要的是所有记录,以便我可以使用 first、last、sum、max 等聚合它们。

Thanks!

谢谢!

采纳答案by idursun

var q = Enumerable.Range(0, 100).GroupBy(x => x/3);

Am I missing something?

我错过了什么吗?

回答by Scott Ivey

This example should work for querying non-numeric collections. It projects an index into the object to be grouped, and then removes it again during the grouping.

这个例子应该适用于查询非数字集合。它将索引投影到要分组的对象中,然后在分组过程中再次将其删除。

var studentQuery2 = students
    .Select((student, index) => new {student, index})
    .GroupBy(g => g.index / 3, i => i.student);

回答by Sudeep

How about a simpler approach:

一个更简单的方法怎么样:

var index = 0;
var grpOf3s = students.GroupBy(x => index++ / 3);

Update:If you are using the Keyvalue of the group item then you will need to convert the group enumerable to a list. Otherwise you will get a different Keyevery time it is accessed.

更新:如果您使用的Key是组项的值,则需要将组可枚举转换为列表。否则Key每次访问都会得到不同的结果。

var index = 0;
var grpOf3s = students.GroupBy(x => index++ / 3).ToList();