Split List into Sublists with LINQ

前端 未结 30 2397
灰色年华
灰色年华 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 07:03

    I think the following suggestion would be the fastest. I am sacrificing the lazyness of the source Enumerable for the ability to use Array.Copy and knowing ahead of the time the length of each of my sublists.

    public static IEnumerable Chunk(this IEnumerable items, int size)
    {
        T[] array = items as T[] ?? items.ToArray();
        for (int i = 0; i < array.Length; i+=size)
        {
            T[] chunk = new T[Math.Min(size, array.Length - i)];
            Array.Copy(array, i, chunk, 0, chunk.Length);
            yield return chunk;
        }
    }
    

提交回复
热议问题