Runar Ovesen Hjerpbakk

Software Philosopher

Split a C# list or array into multiple parts

I needed a method in C# to split a list or an array into multiple parts for batch processing. This is the IEnumerable extension method I came up with:

public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> collection, int batchSize)
{
    var nextbatch = new List<T>(batchSize);
    foreach (T item in collection)
    {
        nextbatch.Add(item);
        if (nextbatch.Count == batchSize)
        {
            yield return nextbatch;
            nextbatch = new List<T>(batchSize);
        }
    }

    if (nextbatch.Count > 0) {
        yield return nextbatch;
    }
}

Example of usage:

var batches = array.Batch(200);
foreach (var batch in batches)
{
    // batch now has 200 items to work with
}