Created
October 21, 2012 07:20
-
-
Save joshka/3926224 to your computer and use it in GitHub Desktop.
GroupByCount
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
// 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