Chunk in C#
Batch a sequence into arrays of at most n.
var items = Enumerable.Range(1, 10);
// Chunk cuts a sequence into arrays of at most n
foreach (var batch in items.Chunk(4))
{
Console.WriteLine($"batch of {batch.Length}: " +
string.Join(",", batch));
}
// the classic use: paging a list for display
var page = items.Chunk(3).ElementAt(1);
Console.WriteLine($"page 2: {string.Join(",", page)}");
How it works
Chunk(4)yields three batches from ten items; the last is short.- Each batch is a real array with a
Length. Chunk(3).ElementAt(1)is page two of a paged list.
Keywords and builtins used here
foreachinstringvar
The run, in numbers
- Lines
- 12
- Characters to type
- 347
- Tokens
- 68
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 45 seconds.
Step 2 of 3 in Slicing, step 5 of 17 in LINQ in depth.