访问Linq查询的基本列表

本文关键字:列表 Linq 查询 访问 | 更新日期: 2023-09-27 18:05:44

我有一个查询,看起来像这样:

var tournamentMatches = community.Tournaments.
    SelectMany(x => x.Rounds.
    SelectMany(y =>  y.Matches)).Where(j => j.Away.Members.Count > 0).
    Select(t =>  new TeamLeagueMatch()
    {
        HomeParticipantId = t.HomeParticipant,
        PlayedOn = t.PlayedOn,
        Result = t.Result,                               
    }).ToList();

我想访问列表的基础部分,以获得锦标赛的名称,所以在Result = t.Result下面,我希望能够放置:

 Name = x.Name

但是,它不识别这个级别的x变量。有没有一种简单的方法来获得我的名字属性,而不诉诸于长时间涉及foreach循环?

类是这样的:

public class Tournament
{
    public string Name { get; set; }
    public IList<TournamentRound> Rounds { get; set; }
}
public class TournamentRound
{
    public DateTime? PlayBy { get; set; }
    public IList<Match> Matches { get; set; }
}
public class Match
{
    public MatchResult Result { get; set; }
    public MatchSide Home { get; set; }
    public MatchSide Away { get; set; }
}
public class MatchSide 
{
    public IList<string> Members { get; set; }
}

访问Linq查询的基本列表

使用查询语法

 var tournamentMatches = (from tournament in community.Tournaments
                from round in tournament.Rounds
                from match in round.Matches
                where match.Away.Members.Count > 0
                select new TeamLeagueMatch
                {
                    HomeParticipantId = match.HomeParticipant,
                    PlayedOn = match.PlayedOn,
                    Result = match.Result,
                    Name = tournament.Name
                }).ToList();

多个from语句将被翻译成如下

community.      
SelectMany(t => t.Rounds, (turnament, round) => new { turnament, round }).
SelectMany(tr => tr.round.Matches, (tr, match) => new {tr.turnament,tr.round,match }).
Where(trm=>trm.match.Away.Members.Count>0).
Select(trm => new TeamLeagueMatch()
                   {
                      HomeParticipantId = trm.match.HomeParticipant,
                      PlayedOn = trm.match.PlayedOn,
                      Result = trm.match.Result,
                      Name = trm.turnament.Name
                   }).ToList();