The following static extension method would make it a straightforward process to break up a list into multiple lists of a specific batch size.
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int noOfItemsPerBatch)
{
decimal iterations = items.Count() / noOfItemsPerBatch;
var roundedIterations = (int)Math.Ceiling(iterations);
var batches = new List<IEnumerable<T>>();
for (int i = 0; i < roundedIterations; i++)
{
var newBatch = items.Skip(i * noOfItemsPerBatch).Take(noOfItemsPerBatch).ToArray();
batches.Add(newBatch);
}
return batches;
}
Example of use
var items = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var batchedItems = items.Batch(4);
Assert.AreEqual(batchedItems.Count() == 3);
Assert.AreEqual(batchedItems[0].Count() == 4);
Assert.AreEqual(batchedItems[1].Count() == 4);
Assert.AreEqual(batchedItems[2].Count() == 2);