Looking for a way to group in sets of n elements with LINQ.
I.e:
{1,2,3,4,5,6,7,8,9}:
- Grouped By 2: {{1,2},{3,4},{5,6},{7,8},{9}}
- Grouped By 3: {{1,2,3},{4,5,6},{7,8,9}}
- Grouped By 4: {{1,2,3,4},{5,6,7,8},{9}}
- Etc...
Only way I can think of doing something like this at the moment is by using an anonymous type to generate a group index, then grouping by that index. I'm looking for a cleaner solution if possible.
Example:
int groupSize = n;
int groupCount = 0;
int groupNum = 0;
IEnumerable<T> items;
IEnumerable<IGrouping<int,T>> groups = items
    .Select(i => new 
    {
      Index = ((groupCount++) % groupSize == 0) ? groupNum++ : groupNum,
      Item = i
    })
    .GroupBy(c => c.Index, d => d.Item);
I'd like to avoid something this nasty if possible.
 
     
     
    