Split List into Sublists with LINQ

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

    It's an old solution but I had a different approach. I use Skip to move to desired offset and Take to extract desired number of elements:

    public static IEnumerable> Chunk(this IEnumerable source, 
                                                       int chunkSize)
    {
        if (chunkSize <= 0)
            throw new ArgumentOutOfRangeException($"{nameof(chunkSize)} should be > 0");
    
        var nbChunks = (int)Math.Ceiling((double)source.Count()/chunkSize);
    
        return Enumerable.Range(0, nbChunks)
                         .Select(chunkNb => source.Skip(chunkNb*chunkSize)
                         .Take(chunkSize));
    }
    

提交回复
热议问题