Rosana Huerta Rosana Huerta - 1 year ago 78
C# Question

Splitting an array using LINQ

I have a collection uni-dimensional like this:


I would like to convert that collection in a bi-dimensional collection like this:


Basically I want to group or split if you want, the array in groups of 'n' members

I can do it with a
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)

Is there any LINQ function to help me to accomplish this??

I was thinking in the
I do not know if they will help me though but they might

Any help will be truly appreciate it =) :**

Answer Source

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());