using System;
using System.Collections.Generic;
class SplitListIntoChunks_CSharp
{
static void Main()
{
var aList = new List<int>();
for (int i = 0; i < 31; i++) {
aList.Add(i);
}
var result = Split(aList, 4);
foreach (var chunk in result) {
Console.WriteLine($"[{string.Join(", ", chunk)}]");
}
}
static IEnumerable<List<T>> Split<T>(List<T> theList, int chunk)
{
// yield return - provide the next value in iteration
for (int i = 0; i < theList.Count; i += chunk) {
yield return theList.GetRange(i, Math.Min(chunk, theList.Count - i));
}
}
}
/*
run:
[0, 1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11]
[12, 13, 14, 15]
[16, 17, 18, 19]
[20, 21, 22, 23]
[24, 25, 26, 27]
[28, 29, 30]
*/