Chunk: New LINQ extensions series

.NET 6 is released recently, it is a good opportunity to mention some of the new LINQ extensions methods. I will post a series of small articles focused on some these new or maybe less known LINQ methods.

In this article I am going to take Chunk LINQ method with some examples so it is easier to understand it.

Prerequisites

To to use these new LINQ extensions you need to download and install this version of .NET 6.

I download and install Visual Studio 2022 in this article.

Chunk

Chunk splits the elements of a sequence into chunks of size at most size.

Example 1

Let take this input as example, we want to pair man1 and woman1, man1 and woman2 and so on:

string[] pairs = new[]
{
    "Man1",
    "Woman1",
    "Man2",
    "Woman2",
    "Man3",
    "Woman3",
};

Lets chunk it by 2

IEnumerable<string[]> chunk = pairs.Chunk(2);

This will result in following output:

List index 0 has
- Array index 0 has Man1
- Array index 1 has Woman1
List index 1 has
- Array index 0 has Man2
- Array index 1 has Woman2
List index 2 has
- Array index 0 has Man3
- Array index 1 has Woman3

Example 2

So lets take another example. In this case we assume we have each 3 values represent x, y, z of sensor data.

var sensor = new[]
{
    1, 2, 3,
    4, 5, 6,
    7, 8, 9
};

By using Chunk(3) we will split each 3rd value in the list. In out case we want to map each 3 value to our model with X, Y, Z

var sensors = sensor.Chunk(3)
    .Select(item => new SensorData(item[0], item[1], item[2]))
    .ToList();

Model example

public class SensorData
{
    public SensorData(int x, int y, int z)
    {
        X = x;
        Y = y;
        Z = z;
    }

    public int X { get; set; }
    public int Y { get; set; }
    public int Z { get; set; }
    public int Calculate => X + Y + Z;
}

Download my examples form GitHub.

Microsoft Chunk documentation

Leave a Comment