C# - LINQ Query for this purpose

本文关键字:this purpose for Query LINQ | 更新日期: 2023-09-27 18:29:08

我有以下带有字段的类

public class Account {
     public int Id { get; set; }
     public string Username { get; set; }
     public float Timezone { get; set; }
}
public class Player {
     public int Id { get; set; }
     public virtual Account Account { get; set; }
     public string Team_Name { get; set; }
}

现在假设我有一个列表<>在名为"玩家"的玩家中,每支队伍有2名玩家,这意味着每支队伍的名称将重复两次。例如,X队有球员A和球员B,这两个项目在列表<>中代表这一点。

我想实现的是根据时区将球队配对,因为每支球队有2名球员,我应该通过访问球员类中的Account.timezone字段来计算每支球队的平均时区,然后找到另一支平均时区最接近的球队来匹配该球队。

示例

C# - LINQ Query for this purpose

假设您有一个Match类,如下所示:

public class Match
{
    public string Team1 { get; set; }
    public string Team2 { get; set; }
}

你可以用LINQ:做这样的事情

var matches =
    Players.GroupBy(player => player.Team_Name) //Group players by team name
        .Select(
            team => //For each team
                new
                {
                    TeamName = team.Key, //Select team name
                    AverageTimezone = //And average time zone
                        team.Average(player => player.Account.Timezone)
                })
        .OrderBy(team => team.AverageTimezone) //Order teams by average time zone
        .Select((team, index) => new {Team = team, Index = index})
        .GroupBy(item => item.Index/2) //Group each two teams together (since the teams are ordered by average timezone, each two teams will have a close timezone)
        .Select(g => g.Select(item => item.Team).ToList())
        .Select(g => new Match
        {
            Team1 = g[0].TeamName,
            Team2 = g[1].TeamName
        })
        .ToList();

您可以使用GroupBy()按Team_Name对List<Player>进行分组,然后从那里开始。

但是,我倾向于创建一个新的实体Team,并为该实体指定Player1和Player2属性,或List<Player> Players属性。然后我会有一个getter TeamTimezone,它可以计算团队中球员的平均时区。

添加一个类来表示团队的概念,可以更清楚地表达程序正在做的事情,使其更易于理解,并减少出现错误的机会。