BlakeH BlakeH - 9 months ago 116
C# Question

Create batches in linq

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.


You don't need to write any code. Use MoreLINQ Batch method, which batches the source sequence into sized buckets (MoreLINQ is available as a NuGet package you can install):

int size = 10;
var batches = sequence.Batch(size);

Which is implemented as:

public static IEnumerable<IEnumerable<TSource>> Batch<TSource>(
                  this IEnumerable<TSource> source, int size)
    TSource[] bucket = null;
    var count = 0;

    foreach (var item in source)
        if (bucket == null)
            bucket = new TSource[size];

        bucket[count++] = item;
        if (count != size)

        yield return bucket;

        bucket = null;
        count = 0;

    if (bucket != null && count > 0)
        yield return bucket.Take(count);