I am attempting to split a list into a series of smaller lists.
My Problem: My function to split lists doesn\'t split them into lists of the correct
I have a generic method that would take any types include float, and it's been unit-tested, hope it helps:
///
/// Breaks the list into groups with each group containing no more than the specified group size
///
///
/// The values.
/// Size of the group.
///
public static List> SplitList(IEnumerable values, int groupSize, int? maxCount = null)
{
List> result = new List>();
// Quick and special scenario
if (values.Count() <= groupSize)
{
result.Add(values.ToList());
}
else
{
List valueList = values.ToList();
int startIndex = 0;
int count = valueList.Count;
int elementCount = 0;
while (startIndex < count && (!maxCount.HasValue || (maxCount.HasValue && startIndex < maxCount)))
{
elementCount = (startIndex + groupSize > count) ? count - startIndex : groupSize;
result.Add(valueList.GetRange(startIndex, elementCount));
startIndex += elementCount;
}
}
return result;
}