使用 LINQ 拆分数组 [英] Splitting an array using LINQ
问题描述
我有一个像这样的一维集合:
I have a collection uni-dimensional like this:
[1,2,4,5.....n]
我想将该集合转换为二维集合,如下所示:
I would like to convert that collection in a bi-dimensional collection like this:
[[1,2,3],
[4,5,6],
...]
基本上我想分组或拆分,如果你想,'n'个成员的数组
Basically I want to group or split if you want, the array in groups of 'n' members
我可以用 foreach
语句来完成,但我目前正在学习 LINQ,所以我不想遍历所有元素并手动创建一个新数组,我想使用 LINQ 功能(如果适用)
I can do it with a foreach
statement, but I am currently learning LINQ so instead of iterating through all elements and create a new array manually I would like to use the LINQ features (if applicable)
是否有任何 LINQ 函数可以帮助我完成此操作??
Is there any LINQ function to help me to accomplish this??
我在考虑 GroupBy
或 SelectMany
我不知道他们是否会帮助我,但他们可能会
I was thinking in the GroupBy
or SelectMany
I do not know if they will help me though but they might
任何帮助将不胜感激 =) :**
Any help will be truly appreciate it =) :**
推荐答案
您可以按索引除以批量大小进行分组,如下所示:
You can group by the index divided by the batch size, like this:
var batchSize = 3;
var batched = orig
.Select((Value, Index) => new {Value, Index})
.GroupBy(p => p.Index/batchSize)
.Select(g => g.Select(p => p.Value).ToList());
这篇关于使用 LINQ 拆分数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!