Method Chunk
Splits the elements of a sequence into chunks of the specified size.
Syntax
public static IEnumerable<TSource[]> Chunk<TSource>(
this IEnumerable<TSource> source,
int size
)
Parameters
-
source
(IEnumerable<TSource>)
The source sequence to chunk. -
size
(int)
The desired size of each chunk. Must be greater than zero.
Returns
-
IEnumerable<TSource[]>
A sequence of arrays, where each array is a chunk of the original sequence.
Exceptions
- ArgumentNullException:
source
is null. - ArgumentOutOfRangeException:
size
is less than or equal to zero.
Remarks
This method yields chunks of the specified size
from the source
sequence.
The last chunk may be smaller than size
if the total number of elements in the sequence is not a multiple of size
.
This is an eagerly evaluated LINQ operator.
Examples
Example 1: Basic usage
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Chunk into arrays of size 3
IEnumerable<int[]> chunks = numbers.Chunk(3);
foreach (int[] chunk in chunks)
{
Console.WriteLine($"[{string.Join(", ", chunk)}]");
}
// Output:
// [1, 2, 3]
// [4, 5, 6]
// [7, 8, 9]
// [10]
}
}
Example 2: Chunking a sequence with fewer elements than the size
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
char[] letters = { 'a', 'b' };
// Chunk into arrays of size 4
IEnumerable<char[]> chunks = letters.Chunk(4);
foreach (char[] chunk in chunks)
{
Console.WriteLine($"[{string.Join(", ", chunk)}]");
}
// Output:
// [a, b]
}
}