Breaking up a collection into smaller fixed size collections with C# .NET
July 4, 2017 1 Comment
Occasionally you may need to break up a large collection into smaller size collections or groups. Consider the following integer list:
List<int> ints = new List<int>() { 1, 4, 2, 5, 2, 6, 5, 43, 6, 234, 645, 2, 12, 45, 13, 5, 3 };
The goal is to break up this list into groups of size 5 and if necessary an additional list for the remaining elements. The following generic method will do the trick:
private IEnumerable<IEnumerable<T>> GroupElements<T>(List<T> fullList, int batchSize) { int total = 0; while (total < fullList.Count) { yield return fullList.Skip(total).Take(batchSize); total += batchSize; } }
Call the method as follows:
var intGroups = GroupElements(ints, 5); foreach (var group in intGroups) { Debug.WriteLine(string.Join(",", group.ToArray())); }
This will give the following printout:
1,4,2,5,2
6,5,43,6,234
645,2,12,45,13
5,3
View the list of posts on LINQ here.
That’s nice, but wouldn’t it be even nicer (and more in line with LINQ in general) if this was written as an extension method?