I'm trying to write an algorithm that yield
s T
s in "batches" of fixed size. (The source could be infinitely long).
Ex.
int[] arr = { 5, 1, 8, 10, 50, 4, 37, 8 };
int size = 2;
foreach(var batch in arr.Batches(size))
{
Console.WriteLine(string.Join(",", batch));
}
----->
5,1
8,10
50,4
37,8
Of course I try something like
public static class Extensions
{
public static IEnumerable<IEnumerable<T>> Batches<T>(this IEnumerable<T> source, int batchSize)
{
for(var mover = source.GetEnumerator(); ; )
{
IEnumerable<T> batch = LimitMoves(mover, batchSize);
if(!batch.Any())
{
yield break;
}
yield return batch;
}
}
private static IEnumerable<T> LimitMoves<T>(IEnumerator<T> mover, int limit)
{
for(int i = 0; i < limit && mover.MoveNext(); ++i)
{
yield return mover.Current;
}
}
}
and get
1,8
50,4
8