Skip to content

Instantly share code, notes, and snippets.

@jasmin-mistry
Created January 28, 2014 13:13
Show Gist options
  • Save jasmin-mistry/8667363 to your computer and use it in GitHub Desktop.
Save jasmin-mistry/8667363 to your computer and use it in GitHub Desktop.
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> collection, int batchSize)
{
List<T> 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment