0 Comments Posted in:

The seventh video in my Exploring MoreLINQ series looks at the Batch extension method, and this is another of my favourites. It simply lets you split your sequence into batches of n elements each. Although this is possible with a few built-in LINQ methods, the MoreLINQ solution is much more elegant:

var batchSize = 2;
// batching with built-in LINQ methods:
var batches = myCollection.
    .Select((item, index) => new { item, index })
    .GroupBy(x => x.index / batchSize)
    .Select(g => g.Select(x => x.item).ToArray());
// with moreLINQ:
batches = myCollection.Batch(batchSize);

For a "real-world" example of where Batch comes in handy, see the solution to Problem 6 (Video editing) in my LINQ Challenge #3.

You can find all videos in this series here.

Want to learn more about LINQ? Be sure to check out my Pluralsight course More Effective LINQ.
Vote on HN