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
This is an old question but this is what I ended up with; it enumerates the enumerable only once, but does create lists for each of the partitions. It doesn't suffer from unexpected behavior when ToArray()
is called as some of the implementations do:
public static IEnumerable> Partition(IEnumerable source, int chunkSize)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (chunkSize < 1)
{
throw new ArgumentException("Invalid chunkSize: " + chunkSize);
}
using (IEnumerator sourceEnumerator = source.GetEnumerator())
{
IList currentChunk = new List();
while (sourceEnumerator.MoveNext())
{
currentChunk.Add(sourceEnumerator.Current);
if (currentChunk.Count == chunkSize)
{
yield return currentChunk;
currentChunk = new List();
}
}
if (currentChunk.Any())
{
yield return currentChunk;
}
}
}