Home Linq - Chunk
Post
Cancel

Linq - Chunk

.NET 6 introduces the new Chunk() extension method on System.Linq namespace to ease splitting an IEnumerable into smaller group of batches, or chunks.

IEnumerable<TSource[]> Chunk<TSource>(this IEnumerable<TSource> source, int size);


Chunking lists


var size = 2;
var numbers = new List<int> { 1, 2, 3, 4, 5 };
var chunks = numbers.Chunk(size);

The usage is quite simple. When giving a collection and the chunk size, the method will return an IEnumerable with the subsets of the collection, with each array being a chunk.


ElementAtOrDefault

Since I’ve used this new extension method with the example below, I think it’s worth covering it a bit.

TSource? ElementAtOrDefault<TSource>(this IEnumerable<TSource> source, int index);

ElementAtOrDefault extension method is different from the standard ElementAt, available on prior .NET versions, once the ElementAtOrDefault method will return the default type of the collection in case the user types an inexistent index, preventing a System.ArgumentOutOfRangeException to occur.

The 5th element

In case you need to get the last element of the list, normally you would have to Count the list in order to know the last index position, but this task was simplified for both ElementAtOrDefault and ElementAt methods with the following sintax:

var numbers = new List<int> { 1, 2, 3, 4, 5 };
var lastElement = numbers.ElementAt(^1); // output = 5
var lastButOneElement = numbers.ElementAt(^2); // output = 4

This simple ^ operator state that the index argument after will act like if your list was reverse, hence ^1 for getting the last element, and so on.


Hands-On


I have written an example using Chunk for performing pagination within a list of objects.

The program requires the user to input the pageSize, which will be used as the index of the chunked data. The totalPage is obviously the count of arrays returned from Chunk(), acting like pages.


Check the project on GitHub



This post is licensed under CC BY 4.0 by the author.