public
Created

GroupByCount

  • Download Gist
GroupingExtensions.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// 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());
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.