Split List into Sublists with LINQ

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

    This following solution is the most compact I could come up with that is O(n).

    public static IEnumerable Chunk(IEnumerable source, int chunksize)
    {
        var list = source as IList ?? source.ToList();
        for (int start = 0; start < list.Count; start += chunksize)
        {
            T[] chunk = new T[Math.Min(chunksize, list.Count - start)];
            for (int i = 0; i < chunk.Length; i++)
                chunk[i] = list[start + i];
    
            yield return chunk;
        }
    }
    

提交回复
热议问题