Is there any way I can separate a List
into several separate lists of SomeObject
, using the item index as the delimiter of each s
I wrote a Clump extension method several years ago. Works great, and is the fastest implementation here. :P
///
/// Clumps items into same size lots.
///
///
/// The source list of items.
/// The maximum size of the clumps 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;
}
}
}