Skip to content

Instantly share code, notes, and snippets.

@joshka
Created October 21, 2012 07:20
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 joshka/3926224 to your computer and use it in GitHub Desktop.
Save joshka/3926224 to your computer and use it in GitHub Desktop.
GroupByCount
// http://devlicio.us/blogs/derik_whittaker/archive/2012/10/20/how-to-split-a-list-into-chunks-fun-code.aspx
static class GroupingExtensions
{
public static IEnumerable<IEnumerable<T>> GroupByCount<T>(this IEnumerable<T> source, int count)
{
if (source == null) throw new ArgumentNullException("source");
return GroupByCountIterator<T>(source, count);
}
static IEnumerable<IEnumerable<T>> GroupByCountIterator<T> (IEnumerable<T> source, int count)
{
using (IEnumerator<T> e = source.GetEnumerator())
{
while (e.MoveNext())
{
yield return TakeIterator<T>(e, count);
}
}
}
static IEnumerable<T> TakeIterator<T>(IEnumerator<T> e, int count)
{
if (count <= 0)
return;
do
{
yield return e.Current;
} while (--count > 0 && e.MoveNext());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment