ChunkBySize

Split the collection into chunks of size at most chunkSize.

Parameters

Returns

int chunkSize

IEnumerable<T> source

IEnumerable<IEnumerable<T>>

Exceptions

Type

When

ArgumentException

chunkSize parameter isn't a positive value.

Usage

A new collection is generated where each element is also a collection with at most chunkSize length.

Splitting a collection in chunks with the same length

//IEnumerable<int> source = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
IEnumerable<IEnumerable<int>> result = source.ChunkBySize(2);

//result = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} }

Splitting a collection in chunks with different lengths

//IEnumerable<int> source = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
IEnumerable<IEnumerable<int>> result = source.ChunkBySize(3);

//result = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9},  {10} }

Last updated