I tried to implement custom Linq Chunk function and found this code example
This function should separate IEnumerable into IEnumerable of concrete size
public static class EnumerableExtentions
{
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int size)
{
using (var enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
int i = 0;
IEnumerable<T> Batch()
{
do yield return enumerator.Current;
while (++i < size && enumerator.MoveNext());
}
yield return Batch();
}
}
}
}
So, I have a question.Why when I try to execute some Linq operation on the result, they are incorrect? For example:
IEnumerable<int> list = Enumerable.Range(0, 10);
Console.WriteLine(list.Batch(2).Count()); // 10 instead of 5
I have an assumption, that it happens because inner IEnumerable Batch() is only triggered when Count() is called, and something goes wrong there, but I don't know what exactly.