Is there a way to organize IEnumerable in a batch in column format using Linq?

In several of my recent projects, I found the need to divide one collection into a mbatch of elements n.

There is an answer to this question that suggests using the morelinq method Batch. This is my preferred solution (no need to reinvent the wheel and all that).

While the method Batchdivides the input file in large string format, is it possible to also write a similar extension that divides the input in major column format? That is, given the input

{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }

you would call ColumnBatch(4)generating output

{
    { 1, 4, 7, 10 },
    { 2, 5, 8, 11 },
    { 3, 6, 9, 12 }
}

Does morelinq already have something similar?

: . 4 3 ( , ).

public static IEnumerable<IEnumerable<T>> ToColumns<T>(this IEnumerable<T> source, int numberOfColumns)

, , .

+3
1
int[] arr = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
int i=0;
var result = arr.GroupBy(x => i++ % 3).Select(g => g.ToList()).ToList();
+4

All Articles