.NET 6 introduced several new features and enhancements that streamline development in C#. One such feature is the .Chunk method provides a simple way to split collections into smaller, manageable parts. In this article, we’ll compare the traditional method of chunking collections using Select, Skip, and Take with the new. Chunk method, highlighting their differences, benefits, and use cases.
What is the.Chunk Method?
The.Chunk method is an extension method for IEnumerable<T> that breaks a collection into chunks of a specified size. This is particularly useful for processing large datasets or dividing work into smaller, more manageable units.
Using the.Chunk Method
Here’s a simple example demonstrating the use of the.Chunk method splits a collection of integers into chunks of a specified size.
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var numbers = Enumerable.Range(1, 20); // Example collection
int chunkSize = 5;
var chunks = numbers.Chunk(chunkSize);
foreach (var chunk in chunks)
{
Console.WriteLine(string.Join(", ", chunk));
}
}
}
Traditional Method: Using Select, Skip, and Take
Before .NET 6, chunking a collection involved using a combination of Select, Skip, and Take.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var numbers = Enumerable.Range(1, 20).ToList(); // Example collection
int chunkSize = 5;
var chunks = ChunkBy(numbers, chunkSize);
foreach (var chunk in chunks)
{
Console.WriteLine(string.Join(", ", chunk));
}
}
public static IEnumerable<List<T>> ChunkBy<T>(List<T> source, int chunkSize)
{
return Enumerable.Range(0, (int)Math.Ceiling(source.Count / (double)chunkSize))
.Select(i => source.Skip(i * chunkSize).Take(chunkSize).ToList());
}
}
Detailed Comparison
1. Simplicity and Readability
- Select, Skip, Take
- Complexity: More complex and verbose.
- Understanding: Requires a good understanding of how Skip and Take work together.
- Manual Calculations: Involves manual calculations to create chunk indices.
- Example:
return Enumerable.Range(0, (int)Math.Ceiling(source.Count / (double)chunkSize)) .Select(i => source.Skip(i * chunkSize).Take(chunkSize).ToList());
- .Chunk
- Simplicity: Simple and concise.
- Directness: The direct method calls with a single parameter for chunk size.
- No Calculations Needed: No need for manual calculations or LINQ chaining.
- Example:
var chunks = numbers.Chunk(chunkSize);

Join the conversation! Your thoughts help the community grow.