从C#中的对象列表创建组

时间:2016-07-26 12:14:09

标签: c# list grouping

我有一个名为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&gt;如果有人有更好的主意。

3 个答案:

答案 0 :(得分:6)

这将随机订购您的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();
}

答案 1 :(得分:1)

我认为最好定义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;

答案 2 :(得分:1)

这个随机组没有重复:

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;
}