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
To split a generic list in to equal chunks use below generic method
private IEnumerable> SplitMaintainingOrder(IEnumerable 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>();
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 recordNumbers = new List() { 1, 2, 3, 4, 5, 6,7,8,9,10,11};
var splitedItems = SplitMaintainingOrder(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..