You can also do this with pure linq by taking advantage of integer arithmetic and the GroupBy
method:
int blockSize = 5;
var group = theList.Select((x, index) => new { x, index })
.GroupBy(x => x.index / blockSize, y => y.x);
foreach (var block in group)
{
// "block" will be an instance of IEnumerable
...
}
There are a number of advantages to this approach which aren't necessarily immediately apparent:
- Execution is deferred, so it's efficient when you're working with conditional processing
- You don't need to know the length of the collection, thus avoiding multiple enumeration while also being generally cleaner than other approaches