Skip to content

Instantly share code, notes, and snippets.

@vbfox
Last active August 29, 2015 14:24
Show Gist options
  • Save vbfox/4e0ab50321a14c324ffe to your computer and use it in GitHub Desktop.
Save vbfox/4e0ab50321a14c324ffe to your computer and use it in GitHub Desktop.
Linq IEnumerable batching
// Variant of MoreLinq Batch implementation
// https://code.google.com/p/morelinq/source/browse/MoreLinq/Batch.cs
public static IEnumerable<IEnumerable<T>> Batch<T>(IEnumerable<T> source, int size)
{
T[] bucket = null;
var count = 0;
foreach (var item in source)
{
if (bucket == null)
{
bucket = new T[size];
}
bucket[count++] = item;
if (count != size)
{
continue;
}
yield return bucket;
bucket = null;
count = 0;
}
if (bucket != null && count > 0)
{
yield return bucket.Take(count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment