Last active
November 25, 2021 14:42
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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