LINQ Chunk

Summary: in this tutorial, you will learn how to use the LINQ Chunk() method to split a sequence into a set of smaller ones, called chunks.

Introduction to the LINQ Chunk() method

The Chunk() method allows you to split a sequence into a set of smaller ones called chunks.

Here’s the syntax of the Chunk() method:

IEnumerable<TSource[]> Chunk<TSource> (
    IEnumerable<TSource> source, 
    int size
);Code language: C# (cs)

The Chunk() method takes two parameters:

  • source is the sequence to be chunked.
  • size is the maximum size of each chunk.

The Chunk() method returns an IEnumerable<TSource[]> that contains the elements of the input sequence split into chunks of size.

The Chunk() method is a lazy-evaluated method, meaning that it does not create the chunks until you access each chunk. It can be useful if you have a large sequence, as it prevents the entire sequence from being loaded into memory at once.

The Chunk() method is useful in the following scenarios:

  • To process a sequence in batches.
  • To parallelize the processing of a collection.
  • To store a collection in a database in chunks.

LINQ Chunk() method example

The following example uses the Chunk() method to chunk a collection of 25 numbers into 3 chunks, each chunk has a maximum of 10 numbers:

using static System.Console;

var numbers = new List<int>(Enumerable.Range(1, 25));
var chunks = numbers.Chunk(10);

foreach (var chunk in chunks)
{
    foreach (var item in chunk)
    {
        Write($"{item}, ");
    }
    WriteLine();
}Code language: C# (cs)

Output:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25,Code language: plaintext (plaintext)

In this example, the chunks contain an IEnumerable<int[]>, where each int[] array contains 10 numbers.

Summary

  • Use LINQ Chunk() method to chunk a sequence into a set of smaller chunks.
Was this tutorial helpful ?