我有一个Team对象列表,Team的一个属性是Player对象列表。
我想从具有特定ID的团队中获取具有特定ID的玩家,例如:
Get the player with ID (player.id) 123 from the Team with ID 987 (team.id)
如何使用LINQ执行此操作?
非常感谢,鲍勃
答案 0 :(得分:4)
var team = teams.FirstOrDefault(teams => teams.ID == 987);
if(team != null) {
var result = team.Players.FirstOrDefault(player => player.ID == 123);
}
答案 1 :(得分:0)
相当简单,但
var list = new List<Team>();
var playerInTeam = list.FirstOrDefault(t=>t.Id==987).Players.FirstOrDefault(p=>p.Id==123);
或者,更一般的解决方案:
public Player GetPlayerInTeam(int playerId, int teamId, IEnumerable<Team> teams)
{
return teams.First(t=>t.Id==teamId).Players.First(p=>p.Id==playerId);
}
答案 2 :(得分:0)
var teams = new List<team>();
var player_team=teams.First(a=>a.id==987).players.First(b=>b.id==123);