I need split list in N sublists with balanced size. For example, i have a list with a 101 elements, and max elements allowed in every sublist is 100. The result should be two sublists, one with 50 elements and one with 51 elements. Actually my code is not working correctly for all cases.
public static void Split()
{
List<int> players = new List<int>();
var totalPlayers = 133;
for (int i = 0; i < totalPlayers; i++)
{
players.Add(i);
}
var maxSizeSubList = 100;
var number = (double)players.Count / maxSizeSubList;
var numberGroupsRound = Math.Ceiling(number);
var playersXGroup = (int) Math.Round(players.Count / numberGroupsRound);
var subLists = SplitList<int>(players, playersXGroup);
}
private static List<List<T>> SplitList<T>(List<T> locations, int nSize = 30)
{
var list = new List<List<T>>();
for (int i = 0; i < locations.Count; i += nSize)
{
list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i)));
}
return list;
}
In this case im getting 3 sublist with, 66, 66 and 1 Result Image
Its dot core 3.1, thanks.