Skip to content

Instantly share code, notes, and snippets.

@JasonElkin
Last active November 25, 2021 14:42
Show Gist options
  • Save JasonElkin/48eac10e98c9f1a2a045a8a9b0737116 to your computer and use it in GitHub Desktop.
Save JasonElkin/48eac10e98c9f1a2a045a8a9b0737116 to your computer and use it in GitHub Desktop.
Evenly distribute the contents of an IEnumerable between a (maximum) number of chunks
public static IEnumerable<IEnumerable<T>> ChunkEvenly<T>(this IEnumerable<T> list, int chunkCount)
{
int groups = 0;
int total = 0;
int count = list.Count();
while (total < count)
{
var size = (int)Math.Ceiling((count - total) / (decimal)(chunkCount - groups));
yield return list.Skip(total).Take(size);
groups++;
total += size;
}
}
void Main()
{
var myList = new List<string>() { "a", "c", "d", "e", "f", "g", "h", "i", "j", "k", "x", "y", "z"};
myList.ChunkEvenly(4);
/*
{
{"a", "c", "d", "e"},
{"f", "g", "h"},
{"i", "j", "k},
{"x", "y", "z"}
}
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment