create batches of 20 from a list in csharp

main.cs
var myList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 };

var batchSize = 20;
var batches = myList.Select((item, index) => new { item, index })
                    .GroupBy(x => x.index / batchSize)
                    .Select(group => group.Select(x => x.item).ToList())
                    .ToList();
370 chars
8 lines

In this example, we are using LINQ to partition the list into batches of 20. The Select method is used to include the current index along with each item in the list. The GroupBy method then groups these items based on their index divided by the batch size. Finally, the Select method is called again to project the groups of items into lists.

The output will be a list of lists, where each inner list contains 20 elements (except for the last batch which may contain fewer).

gistlibby LogSnag