访问Linq查询的基本列表

时间:2016-09-06 08:51:29

标签: c# .net linq

我有一个如下所示的查询:

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

2 个答案:

答案 0 :(得分:3)

使用查询语法:

 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();

答案 1 :(得分:1)

multi 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();