Split any IEnumerable into fixed-size chunks with a simple static method or LINQ-style extension.
dotnet add package Philiprehberger.ChunkListSplit any IEnumerable into fixed-size chunks with a simple static method or LINQ-style extension.
dotnet add package Philiprehberger.ChunkList
using Philiprehberger.ChunkList;
var numbers = Enumerable.Range(1, 10);
// Static method
foreach (var chunk in EnumerableChunker.Chunk(numbers, 3))
{
Console.WriteLine(string.Join(", ", chunk));
}
// 1, 2, 3
// 4, 5, 6
// 7, 8, 9
// 10
// Extension method
var chunks = numbers.ChunkBy(4).ToList();
// chunks[0] == [1, 2, 3, 4]
// chunks[1] == [5, 6, 7, 8]
// chunks[2] == [9, 10]
// Works with any sequence
var words = new[] { "a", "b", "c", "d", "e" };
var pairs = words.ChunkBy(2);
// ["a","b"], ["c","d"], ["e"]
using Philiprehberger.ChunkList;
var items = Enumerable.Range(1, 10);
var pairs = EnumerableChunker.Chunk(items, 2);
// [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
using Philiprehberger.ChunkList;
var names = new[] { "Alice", "Bob", "Charlie", "Dave", "Eve" };
foreach (var group in names.ChunkBy(2))
{
Console.WriteLine(string.Join(", ", group));
}
// Alice, Bob
// Charlie, Dave
// Eve
using Philiprehberger.ChunkList;
var empty = Array.Empty<int>().ChunkBy(3); // yields nothing
var small = new[] { 1, 2 }.ChunkBy(5); // [[1, 2]] — single chunk
EnumerableChunker| Method | Description |
|---|---|
Chunk<T>(IEnumerable<T> source, int size) | Yield IReadOnlyList<T> chunks of at most size elements |
ChunkExtensions| Method | Description |
|---|---|
ChunkBy<T>(this IEnumerable<T> source, int size) | Extension method — same as EnumerableChunker.Chunk |
Notes:
size elements.ArgumentOutOfRangeException if size is zero or negative.dotnet build src/Philiprehberger.ChunkList.csproj --configuration Release
If you find this project useful: