Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to organise an IEnumerable into batches in column-major format using Linq?

Tags:

c#

linq

In several of my most recent projects, I've found the need to divide a single collection up into m batches of n elements.

There is an answer to this question that suggests using morelinq's Batch method. That is my preferred solution (no need to re-invent the wheel and all that).

While the Batch method divides the input up in row-major format, would it also be possible to write a similar extension that divides the input up in column-major format? That is, given the input

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

you would call ColumnBatch(4), generating an output of

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

Does morelinq already offer something like this?

UPDATE: I'm going to change the convention slightly. Instead of using an input of 4, I'll change it to 3 (the number of batches rather than the batch size).

The final extension method will have the signature

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

which should be clear to whoever is implementing the method, and does not require multiple enumerations.

like image 793
Rob Lyndon Avatar asked Jan 24 '26 13:01

Rob Lyndon


1 Answers

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();
like image 162
L.B Avatar answered Jan 26 '26 03:01

L.B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!