开发者

LINQ Numerical Grouping [duplicate]

This question already has answers here: Split List into Sublists with LINQ (34 answers) Closed 8 years ago.

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 th开发者_运维技巧at 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜