Split List into Sublists with LINQ

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

    This question is a bit old, but I just wrote this, and I think it's a little more elegant than the other proposed solutions:

    /// 
    /// Break a list of items into chunks of a specific size
    /// 
    public static IEnumerable> Chunk(this IEnumerable source, int chunksize)
    {
        while (source.Any())
        {
            yield return source.Take(chunksize);
            source = source.Skip(chunksize);
        }
    }
    

提交回复
热议问题