Skip to content

Instantly share code, notes, and snippets.

Created December 3, 2015 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/9d1d9abe6d8b9fca61c2 to your computer and use it in GitHub Desktop.
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
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