• Sun. Dec 22nd, 2024

How to chunk data using LINQ in C#

Byadmin

Dec 14, 2024



Using Chunk to split an array of integers in C#

Let us understand this with a code example. Consider the following code, which uses the Chunk extension method to divide an array of integers into chunks of equal sizes.

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
var chunks = numbers.Chunk(5);
int counter = 0;
foreach (var chunk in chunks)
{
Console.WriteLine($”Chunk #{++counter}”);
Console.WriteLine(string.Join(“, “, chunk));
}

In the preceding code example, we create an array of 15 integers, then use the Chunk method to split the array into chunks of equal sizes, i.e., five elements in this example. Finally, we display the integers contained in each chunk at the console.



Source link