Created
January 28, 2018 12:51
-
-
Save mattwhetton/c6b07192eb36272113aba13fa957fbe2 to your computer and use it in GitHub Desktop.
Extension method for cutting an enumerable into batches
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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