Can someone suggest a way to create batches of a certain size in linq?
Ideally I want to be able to perform operations in chunks of some configurable amount.
Same approach as MoreLINQ, but using List instead of Array. I haven't done benchmarking, but readability matters more to some people:
public static IEnumerable> Batch(this IEnumerable source, int size)
{
List batch = new List();
foreach (var item in source)
{
batch.Add(item);
if (batch.Count >= size)
{
yield return batch;
batch.Clear();
}
}
if (batch.Count > 0)
{
yield return batch;
}
}