I have an extension that explodes List into groups, which makes displaying content easy. Here is the extension code
public static List<List<T>> GroupItems<T>(this List<T> items, int totalGroups)
{
List<List<T>> groups = null;
if (items != null)
{
groups = new List<List<T>>();
int itemsPerGroup = (int)Math.Ceiling((double)items.Count / totalGroups);
if (itemsPerGroup > items.Count)
{
List<T> group = new List<T>(items);
groups.Add(group);
}
else
{
for (int i = 0; i < totalGroups; i++)
{
List<T> group = items.Skip(i * itemsPerGroup).Take(itemsPerGroup).ToList();
groups.Add(group);
}
}
}
return groups;
}
Here is the scenario:
I have a List and it has 13 items (items may vary).
In this particular instance, since i am exploding the list into 4 groups, i am getting
- group 1: 4 items
group 2: 4 items
group 3: 4 items
- group 4: 1 item
The 4 items per group is coming from
int itemsPerGroup = (int)Math.Ceiling((double)items.Count / totalGroups);
Now this is wrong, ideally i should have
- group 1: 4 items
- group 2: 3 items
- group 3: 3 items
- group 4: 3 items
Same way, when i try to explode this into 6 groups, i get
- group 1: 3 items
- group 2: 3 items
- group 3: 3 items
- group 4: 3 items
- group 5: 1 item
- group 6: 0 items
you can see this in the attached pic here as well
Ideally this should have
- group 1: 3 items
- group 2: 2 items
- group 3: 2 items
- group 4: 2 items
- group 5: 2 items
- group 6: 2 items
What am i missing here? How can i fix this issue?