Skip to content

Instantly share code, notes, and snippets.

@mattwhetton
Created January 28, 2018 12:51
Show Gist options
  • Save mattwhetton/c6b07192eb36272113aba13fa957fbe2 to your computer and use it in GitHub Desktop.
Save mattwhetton/c6b07192eb36272113aba13fa957fbe2 to your computer and use it in GitHub Desktop.
Extension method for cutting an enumerable into batches
public static class EnumerableExtensions
{
public static IEnumerable<IEnumerable<T>> Batches<T>(this IEnumerable<T> items, int batchSize)
{
if (batchSize <= 0)
{
throw new ArgumentException("Batch size must be greater than 0");
}
var itemsList = items as IList<T> ?? items.ToList();
var itemCount = itemsList.Count;
var numBatches = Math.Ceiling((decimal) itemCount / batchSize);
for (int i = 0; i < numBatches; i++)
{
yield return itemsList.Skip(i * batchSize).Take(batchSize);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment