IEnumerable.Chunk
Splits an enumerable into chunks of a specified size.
Source
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> list, int chunkSize)
{
if (chunkSize <= 0)
{
throw new ArgumentException("chunkSize must be greater than 0.");
}
while (list.Any())
{
yield return list.Take(chunkSize);
list = list.Skip(chunkSize);
}
}
Example
var list = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
var chunks = list.Chunk(3);
// returns { { 1, 2, 3 }, { 4, 5, 6 }, { 7 } }