从C#中的对象列表创建组
本文关键字:列表 创建组 对象 | 更新日期: 2023-09-27 17:58:43
我有一个名为Team的对象列表,我想创建它们的组,但不是按顺序随机的。将组编号提供给功能以及列表
public List<List<Team>> GenerateGroups(List<Team> teams, int amount)
{
List<List<Team>> result = new List<List<Team>>();
for (int i = 0; i < amount; ++i)
result.Add(new List<Team>());
foreach(Team team in teams)
{
//Add something
}
return result;
}
我被困在这里了。我不知道如何添加团队。此外,如果有人能浓缩我的代码,那将非常有帮助。如果有人有更好的想法,我不需要它来返回List>。
这将随机排序teams
,然后将它们分组。列表中输出组的数量取决于amount
参数:
public static List<List<Team>> GenerateGroups(List<Team> teams, int amount)
{
return teams.OrderBy(item => Guid.NewGuid())
.Select((item, index) => new { Item = item, GroupIndex = index % amount })
.GroupBy(item => item.GroupIndex,
(key, group) => group.Select(groupItem => groupItem.Item).ToList())
.ToList();
}
也可以随机使用Random
类,但我会用它来创建订单,而不是group by
public static List<List<Team>> GenerateGroups(List<Team> teams, int amount)
{
Random random = new Random();
return teams.OrderBy(item => random.NextDouble())
.Select((item, index) => new { Item = item, GroupIndex = index % amount })
.GroupBy(item => item.GroupIndex,
(key, group) => group.Select(groupItem => groupItem.Item).ToList())
.ToList();
}
这一个给出了没有重复的随机组:
private static Random _rnd = new Random();
private static Team GetAndRemoveRandomTeam(List<Team> allTeams)
{
int randomIndex = _rnd.Next(allTeams.Count);
Team randomTeam = allTeams[randomIndex];
allTeams.RemoveAt(randomIndex);
return randomTeam;
}
public static List<List<Team>> GenerateGroups(List<Team> teams, int amount)
{
int teamCount = (int) teams.Count/amount;
List<Team> allteams = teams.ToList(); // copy to be able to remove items
if (teamCount == 0)
return new List<List<Team>> {allteams};
List<List<Team>> allTeamGroups = new List<List<Team>>();
List<Team> thisTeam = new List<Team>();
while (allteams.Count > 0)
{
if (thisTeam.Count == amount)
{
allTeamGroups.Add(thisTeam);
thisTeam = new List<Team>();
}
thisTeam.Add(GetAndRemoveRandomTeam(allteams));
}
allTeamGroups.Add(thisTeam);
return allTeamGroups;
}
我认为您最好定义Group
类,如:
class Group {
List<Team> teams;
}
关于添加团队:
Random rnd = new Random();
List<Group> groups = new List<Group>();
for (int i = 0; i < amount; ++i)
groups.Add(new Group());
foreach(Team team in teams)
{
int index = rnd.Next(0, amount);
groups[index].Add(team);
}
return groups;