.NET 6 introduces the new Chunk()
extension method on System.Linq
namespace to ease splitting an IEnumerable
into smaller group of batches, or chunks
.
Chunking lists
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.
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:
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.