Split List into Sublists with LINQ

前端 未结 30 2462
灰色年华
灰色年华 2020-11-21 06:26

Is there any way I can separate a List into several separate lists of SomeObject, using the item index as the delimiter of each s

30条回答
  •  野性不改
    2020-11-21 06:51

    We can improve @JaredPar's solution to do true lazy evaluation. We use a GroupAdjacentBy method that yields groups of consecutive elements with the same key:

    sequence
    .Select((x, i) => new { Value = x, Index = i })
    .GroupAdjacentBy(x=>x.Index/3)
    .Select(g=>g.Select(x=>x.Value))
    

    Because the groups are yielded one-by-one, this solution works efficiently with long or infinite sequences.

提交回复
热议问题