Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this linq code that splits a sequence work?

Tags:

c#

linq

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; 
    } 
} 

enter image description here

like image 529
Aaron Anodide Avatar asked Apr 20 '12 00:04

Aaron Anodide


2 Answers

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...

like image 194
Keith Rousseau Avatar answered Nov 13 '22 10:11

Keith Rousseau


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());
like image 29
jason Avatar answered Nov 13 '22 12:11

jason