gpt4 book ai didi

C# - 为此目的的 LINQ 查询

转载 作者:行者123 更新时间:2023-11-30 20:39:05 25 4
gpt4 key购买 nike

我有以下带有这些字段的类

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

现在假设我有一个名为 Players 的 Player 列表<>,每支球队有 2 名球员,这意味着每个 Team_Name 将重复两次。例如。 Team X 有 Player A 和 Player B,List<> of Player 中的两个条目来表示。

我想要实现的是根据时区将团队相互配对,因为每个团队都有 2 名球员,我应该通过访问 Account.Timezone 球员类中的字段来计算每个团队的平均时区,然后找到另一个最接近平均值的团队使团队与他们相匹配的时区。

Example

最佳答案

假设您有一个像这样的 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();

关于C# - 为此目的的 LINQ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34619599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com