Breaking up a collection into smaller fixed size collections with C# .NET
April 15, 2015 3 Comments
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.
Hello Andras,
In the code above I’m getting the error:
Severity Code Description Project File Line Suppression State
Error CS1061 ‘List’ does not contain a definition for ‘Skip’ and no extension method ‘Skip’ accepting a first argument of type ‘List’ could be found (are you missing a using directive or an assembly reference?)
Hi Fernando, do you have the default using statements in your C# file? System, System.Collections.Generic, System.Linq and System.Text? //Andras
Hi Andras,
Thanks that was the problem.
Great blog, congratulations