First time writing a generic method here. Input a List<T>
and an int
value and output a List<List<T>>
with each member List<T>
of the provided int
input.
No doubt there are easier / less verbose ways of handling this via LINQ
but I wanted to try my hand with a generic method. Please let me know of any ways that I could improve this method.
static List<List<T>> SplitIntoChunks<T>(List<T> fullBatch, int chunkSize)
{
if (chunkSize <= 0)
{
throw new ArgumentOutOfRangeException("Chunk size cannot be less than or equal to zero.");
}
if (fullBatch == null)
{
throw new ArgumentNullException("Input to be split cannot be null.");
}
int numOfChunks = fullBatch.Count / chunkSize;
//handles uneven number of items within the full batch to ensure none at the end are missed
if (fullBatch.Count % chunkSize > 0)
{
numOfChunks++;
}
int cellCounter = 0;
List<List<T>> splitChunks = new List<List<T>>();
for (int chunkNum = 0; chunkNum < numOfChunks; chunkNum++)
{
var chunk = new List<T>();
for (int index = 0; index < chunkSize; index++)
{
if (index < fullBatch.Count)
{
chunk.Add(fullBatch[index]);
cellCounter++;
}
}
splitChunks.Add(chunk);
}
return splitChunks;
}