Skip to content

Instantly share code, notes, and snippets.

@ElanHasson
Created July 7, 2021 23:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ElanHasson/2f223a244e53b4758c6ac87f3505fd42 to your computer and use it in GitHub Desktop.
Save ElanHasson/2f223a244e53b4758c6ac87f3505fd42 to your computer and use it in GitHub Desktop.
A set of extensions for batching in Linq
public static class BatchEnumerableExtensions
{
public static IEnumerable<IList<T>> InBatchesOf<T>(this IEnumerable<T> items, int batchSize)
{
var batch = new List<T>(batchSize);
foreach (var item in items)
{
batch.Add(item);
if (batch.Count >= batchSize)
{
yield return batch;
batch = new List<T>(batchSize);
}
}
if (batch.Count != 0)
{
yield return batch;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment