Inspired By @dicegiuy30's implementation, I wanted to create a version that only iterates over the source once and doesn't build the whole result set in memory to compensate. Best I've come up with is this:
public static IEnumerable> Split2(this IEnumerable source, int chunkSize) {
var chunk = new List(chunkSize);
foreach(var x in source) {
chunk.Add(x);
if(chunk.Count <= chunkSize) {
continue;
}
yield return chunk;
chunk = new List(chunkSize);
}
if(chunk.Any()) {
yield return chunk;
}
}
This way I build each chunk on demand. I wish I should avoid the List as well and just stream that that as well, but haven't figured that out yet.