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.

Advertisements

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

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

  1. Fernando Lugao says:

    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?)

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: