I've been using a method for splitting collections into batches form this answer - https://stackoverflow.com/a/17598878/1012739:
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int size) {
using (IEnumerator<T> enumerator = source.GetEnumerator())
while (enumerator.MoveNext())
yield return TakeIEnumerator(enumerator, size);
}
private static IEnumerable<T> TakeIEnumerator<T>(IEnumerator<T> source, int size) {
int i = 0;
do yield return source.Current;
while (++i < size && source.MoveNext());
}
When iterating over the results of Batch<T>
one gets the expected number of collections, but when calling Count
or ToList
the outer collection length is reported:
var collection = new int[10];
var count = 0;
foreach(var batch in collection.Batch(2))
++count;
Assert.AreEqual(5, count); // Passes
// But
Assert.AreEqual(5, collection.Batch(2).Count()); // Fails
Assert.AreEqual(5, collection.Batch(2).ToList().Count); // Fails
How does this work and is the a way to fix it?