Before .NET 6, splitting a list into smaller batches required messy math with Skip and Take. Chunk does it in one line.
Many APIs and Databases have limits on payload size (e.g., 'You can only insert 500 rows at a time'). Chunk allows you to process a massive list in bite-sized pieces.
// Split 10,000 IDs into batches of 100
var batches = largeListOfIds.Chunk(100);
foreach (var batch in batches) {
// Process 100 items...
await SendBatchToApi(batch);
}
Chunk is lazy-evaluated. It doesn't create all the batches in memory at once. It yields them one by one as you iterate. This allows you to process millions of items with a fixed, small memory footprint.
Q: "What happens to the last chunk?"
Architect Answer: "If you have 105 items and you chunk by 10, you will get 10 chunks of 10, and a final chunk of 5. The last chunk is never 'padded'βit simply contains the remaining elements. This makes it safe to use for any list size without extra logic."