tags:

views:

74

answers:

2

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.

+6  A: 
var values = new []{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };

groups = values.Select((v, i) => new { index = i, value = v })
    .GroupBy(k => k.index / n, e => e.value);
Yuriy Faktorovich
!!! The Index, I forgot `.Select` could return it! Thankyou!
Aren
A: 

I've answered a similar question here. It still uses an anonymous type, but I don't think it's as "nasty" as your example.

GWB