I am trying to split a collection into multiple collections while maintaining a sort I have on the collection. I have tried using the following extension method, but it breaks
As I understand you want to break enumerable on several parts with equal size and without breaking the order of your elements. It looks like the only choice is to get the length of your input enumerable first, so you would need at least two iterations through the enumerable.
To split a generic list in to equal chunks use below generic method
private IEnumerable<IEnumerable<T>> SplitMaintainingOrder<T>(IEnumerable<T> list, int columnCount)
{
var elementsCount = list.Count();
int rowCount = elementsCount / columnCount;
int noOfCells = elementsCount % columnCount;
int finalRowCount = rowCount;
if (noOfCells > 0)
{
finalRowCount++;
}
var toreturn = new List<IEnumerable<T>>();
var pushto = 0;
for (int j = 0; j < columnCount; j++)
{
var start = j;
int i = 0;
var end = i;
for (i = 0; i < finalRowCount; i++)
{
if ((i < rowCount) || ((i == rowCount) && (j < noOfCells)))
{
start = j;
end = i;
}
}
toreturn.Add(list.Skip(pushto).Take(end + 1));
pushto += end + 1;
}
return toreturn;
}
List<int> recordNumbers = new List<int>() { 1, 2, 3, 4, 5, 6,7,8,9,10,11};
var splitedItems = SplitMaintainingOrder<int>(recordNumbers , 4);
Output will be:
List 1 : 1,2,3
List 2 : 4,5,6
List 3 : 7,8,9
List 4 : 10,11
~Happy coding..