using System.Linq;
using System.Diagnostics;
namespace System.Collections.Generic
{
public static class EnumeratorExtensions
{
///
/// Groups items into same size lots.
///
///
/// The source list of items.
/// The maximum size of the groups to make.
/// A list of list of items, where each list of items is no bigger than the size given.
public static IEnumerable> Clump(this IEnumerable source, int size)
{
if (source == null)
throw new ArgumentNullException("source");
if (size < 1)
throw new ArgumentOutOfRangeException("size", "size must be greater than 0");
return ClumpIterator(source, size);
}
private static IEnumerable> ClumpIterator(IEnumerable source, int size)
{
Debug.Assert(source != null, "source is null.");
T[] items = new T[size];
int count = 0;
foreach (var item in source)
{
items[count] = item;
count++;
if (count == size)
{
yield return items;
items = new T[size];
count = 0;
}
}
if (count > 0)
{
if (count == size)
yield return items;
else
{
T[] tempItems = new T[count];
Array.Copy(items, tempItems, count);
yield return tempItems;
}
}
}
}
}