BMills BMills - 1 year ago 67
C# Question

Accessing the base list of a Linq query

I have a query that looks like this:

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,

I'm wanting to access the base part of the list, to get the name of the tournament, so below
Result = t.Result
I'd like to be able to put:

Name = x.Name

However, it doesn't recognise the x variable at this level. Is there an easy way to get my name property without resorting to long involved foreach loops?

The classes look this:

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

Answer Source

Using query syntax and let keyword:

 var tournamentMatches = (from tournament in community.Tournaments
                from round in tournament.Rounds
                from match in round.Matches
                let name = tournament.Name
                where match.Away.Members.Count > 0
                select new TeamLeagueMatch
                    HomeParticipantId = match.HomeParticipant,
                    PlayedOn = match.PlayedOn,
                    Result = match.Result,
                    Name = name
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download