Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Enumerable.Chunk: practical reference

Enumerable.Chunk: practical reference: Deferred enumeration groups consecutive elements into new arrays whose length is at most size. The final array can be shorter.

Version: .NET 6+; verified on .NET 10.0.14

Syntax

source.Chunk(/* overload-specific arguments */)

Deferred enumeration groups consecutive elements into new arrays whose length is at most size. The final array can be shorter.

Use it to batch data before a bulk operation, remembering that every chunk is a separate array.

Starting another enumeration rereads the source and creates new arrays. It does not retain a shared reusable buffer.

A size below 1 throws ArgumentOutOfRangeException. An infinite source can keep producing chunks forever.

The complete program actually uses Enumerable.Chunk; its exact expected stdout is 2,2,1.

Examples

using System;
using System.Collections.Generic;
using System.Linq;

Console.WriteLine(string.Join(",", Enumerable.Range(1, 5).Chunk(2).Select(chunk => chunk.Length)));

Result

2,2,1

The complete program actually uses `Enumerable.Chunk`; its exact expected stdout is `2,2,1`.

Sources