Split List into Sublists with LINQ

前端 未结 30 2935
灰色年华
灰色年华 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:50

    What about this one?

    var input = new List { "a", "g", "e", "w", "p", "s", "q", "f", "x", "y", "i", "m", "c" };
    var k = 3
    
    var res = Enumerable.Range(0, (input.Count - 1) / k + 1)
                        .Select(i => input.GetRange(i * k, Math.Min(k, input.Count - i * k)))
                        .ToList();
    

    As far as I know, GetRange() is linear in terms of number of items taken. So this should perform well.

提交回复
热议问题