Created
September 20, 2013 14:31
-
-
Save brenoferreira/6638483 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
static class EnumEx | |
{ | |
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int maxItemsByPart) | |
{ | |
return SplitImpl(list, maxItemsByPart, 0, new List<IEnumerable<T>>()); | |
} | |
public static IEnumerable<IEnumerable<T>> SplitImpl<T>( | |
IEnumerable<T> list, | |
int maxItemsByPart, | |
int itensSoFar, | |
List<IEnumerable<T>> accumulator) | |
{ | |
var listSize = list.Count(); | |
if (listSize <= itensSoFar) return accumulator; | |
else | |
{ | |
var maxInIteration = GetMaxInIteration(listSize, maxItemsByPart, itensSoFar); | |
accumulator.Add(list.Skip(itensSoFar).Take(maxInIteration)); | |
return SplitImpl( | |
list, | |
maxInIteration, | |
itensSoFar + maxInIteration, | |
accumulator); | |
} | |
} | |
public static int GetMaxInIteration(int listSize, int maxByPart, int itensSoFar) | |
{ | |
var parts = listSize / maxByPart + (listSize % maxByPart > 0 ? 1 : 0); | |
var itemsByPart = listSize / parts; | |
var restItems = listSize % parts; | |
return itemsByPart + (restItems > 0 ? 1 : 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment