Last active
August 29, 2015 14:24
-
-
Save vbfox/4e0ab50321a14c324ffe to your computer and use it in GitHub Desktop.
Linq IEnumerable batching
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
// 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