Created
December 3, 2015 23:40
-
-
Save anonymous/9d1d9abe6d8b9fca61c2 to your computer and use it in GitHub Desktop.
I feel like this is something that should already exist in System.Linq
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
using System; | |
using System.Collections.Generic; | |
public static class GroupingExtensions | |
{ | |
public static IEnumerable<IEnumerable<T>> BreakIntoGroups<T>(this IEnumerable<T> sequence, int groupSize) | |
{ | |
if (sequence == null) | |
{ | |
throw new ArgumentNullException("sequence"); | |
} | |
if (groupSize <= 0) | |
{ | |
throw new ArgumentOutOfRangeException("groupSize", groupSize, "Groups must be of size 1 or greater"); | |
} | |
IEnumerator<T> enumerator = sequence.GetEnumerator(); | |
while (enumerator.MoveNext()) | |
{ | |
yield return GetNextGroup(enumerator, groupSize); | |
} | |
} | |
private static IEnumerable<T> GetNextGroup<T>(this IEnumerator<T> enumerator, int groupSize) | |
{ | |
int remainingElements = groupSize; | |
do | |
{ | |
yield return enumerator.Current; | |
remainingElements -= 1; | |
} while (remainingElements > 0 && enumerator.MoveNext()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment