Divide an integer into groups with C# .NET

Imagine that we have an integer and we want to divide it into equal groups of another integer and put any remainder to the end of the group. E.g. if we want to divide 100 into groups/batches of at most 15 then we’ll have the following array of integers:

15, 15, 15, 15, 15, 10

The following C# function will perform exactly that function:

private IEnumerable<int> BatchInteger(int total, int batchSize)
	if (batchSize == 0)
		yield return 0;

	if (batchSize >= total)
		yield return total;
		int rest = total % batchSize;
		int divided = total / batchSize;
		if (rest > 0)
			divided += 1;

		for (int i = 0; i < divided; i++)
			if (rest > 0 && i == divided - 1)
				yield return rest;
				yield return batchSize;

If the batch size is 0 then we return 0. Also if the batch size is is equal to or bigger than the total then we return the batch size. Otherwise we keep returning the batch size until the remainder is smaller than that. At which point we return the remainder.


var batch = BatchInteger(100, 15);
foreach (int item in batch)

The result is exactly as we expect:


View all various C# language feature related posts here.

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

2 Responses to Divide an integer into groups with C# .NET

  1. Michael says:

    Hi, it seems you have lost one 15 while copying it. Code works fine.
    I’m a big fan of your great knowledge-project, I learn a lot. Thank you very much.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s


A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

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: