If using .NET Core 5, Chunk internally uses yield. Try the following example here.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
public class Program
{
public static void Main()
{
IEnumerable<string[]> chunk = DateTimeFormatInfo.CurrentInfo!.MonthNames[..^1].ToList().Chunk(2);
List<string[]> list = chunk.ToList();
for (int index = 0; index < list.LongCount(); index++)
{
Console.WriteLine(index);
foreach (var name in list[index])
{
Console.WriteLine($"\t{name}");
}
}
}
}
MS Code
private static IEnumerable<TSource[]> ChunkIterator<TSource>(IEnumerable<TSource> source, int size)
{
using IEnumerator<TSource> e = source.GetEnumerator();
while (e.MoveNext())
{
TSource[] chunk = new TSource[size];
chunk[0] = e.Current;
int i = 1;
for (; i < chunk.Length && e.MoveNext(); i++)
{
chunk[i] = e.Current;
}
if (i == chunk.Length)
{
yield return chunk;
}
else
{
Array.Resize(ref chunk, i);
yield return chunk;
yield break;
}
}
}
Other uses, iterating a DataReader to return each item in the loop retrieving data.