Breaking up a collection into smaller fixed size collections with C# .NET

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Breaking up a collection into smaller fixed size collections with C# .NET

  1. przemo says:

    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?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: