0

I got a List of Team objects, and one of the properties of a Team is a List of Player objects.

I want to grab a player with a specific ID from a team with a specific ID, for example:

Get the player with ID (player.id) 123 from the Team with ID 987 (team.id)

How can I do this using LINQ?

Many thanks in advance, Bob

1
  • 1
    That's quite straightforward with the Where method - what exactly is the problem? Commented Mar 29, 2015 at 9:48

3 Answers 3

4
var team = teams.FirstOrDefault(teams => teams.ID == 987);
if(team != null) {
    var result = team.Players.FirstOrDefault(player => player.ID == 123);
}
Sign up to request clarification or add additional context in comments.

Comments

0
var teams = new List<team>();
var player_team=teams.First(a=>a.id==987).players.First(b=>b.id==123);

Comments

0

Rather simple, though

var list = new List<Team>();
var playerInTeam = list.FirstOrDefault(t=>t.Id==987).Players.FirstOrDefault(p=>p.Id==123);

Or, more general soultion:

public Player GetPlayerInTeam(int playerId, int teamId, IEnumerable<Team> teams)
{
    return teams.First(t=>t.Id==teamId).Players.First(p=>p.Id==playerId);
}

1 Comment

You shouldn't use Where for this. Single(OrDefault), First(OrDefault) would be better I think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.