Chunk an IEnumerable into fixed-size List batches
C#
using System;
using System.Collections.Generic;
static IEnumerable<List<T>> Chunk<T>(IEnumerable<T> source, int size)
{
if (size <= 0)
throw new ArgumentOutOfRangeException(nameof(size));
var batch = new List<T>(size);
foreach (var item in source)
{
batch.Add(item);
if (batch.Count < size)
continue;
yield return batch;
batch = new List<T>(size);
}
if (batch.Count > 0)
yield return batch;
}