I've been staring at this code which I found in another question (copied verbatim below) and I know it's not much, but it's escaping me how the i++ % parts works.
void Main()
{
int[] a = new [] { 10, 3, 5, 22, 223 };
a.Split(3).Dump();
}
static class LinqExtensions
{
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
{
int i = 0;
var splits = from item in list
group item by i++ % parts into part
select part.AsEnumerable();
return splits;
}
}
It groups the items into the number of parts that you specify. The i++ will increment for each item and apply the modulus operator so that it puts it in the correct number of buckets. So the first item goes in bucket 0, 2nd in bucket 1, 3rd in bucket 2, 4th in bucket 0, etc...
While Keith Rousseau is correct, I would argue that the idea is a rather bad way to achieve this. You can achieve it more purely (i.e., without having to mutate a captured variable) via:
var splits = list.Select((item, index) => new { Item = item, Index = index })
.GroupBy(pair => pair.Index % parts, element => element.Item)
.Select(group => group.AsEnumerable());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With