我希望更多地了解LINQ并使用它,所以在这里进行一些自我开发工作......
我有一个如下对象:
public class Player(){
public string Name{get;set;}
public Club currentClub{get;set;}
public IEnumerable<Club> previousClubs{get;set;}
}
现在,鉴于一个球员名单,我想选择以前为各种俱乐部效力的球员,我可以通过嵌套的几个foreach声明轻松地做到这一点 - 但我想这样做LINQ ...
我试过了,但没有从中回复:
var prevClubs =
from player in players
from clubOriginal in player.previousClubs
from clubSecond in player.previousClubs
from clubThird in player.previousClubs
where clubOriginal.ID == 1
where clubSecond.ID == 2
where clubThird.ID == 3
select new HistoryOfPlayer{
firstClub == clubOriginal.Name,
secondClub == clubSecond.Name,
thirdClub == clubThird.Name
}
在我出错的地方有任何帮助吗?数据肯定是存在的,因为当我有一个环绕循环中的球杆的foreach循环循环球员并且我返回所有为球杆1,2和球员效力的球员的集合。 3有数据......
实际上它应该返回一个HistoryOfPlayer对象的几个实例,所有实例都包含相同3个俱乐部的名称(假设它们与ID相关联) - 正如我所说,它有点自学,所以试图将其应用于运动,所以它有点在我脑海中!!
有人可以帮忙吗?
答案 0 :(得分:4)
你可以让它变得更有活力
List<int> clubIds = new List<int> { 1, 2, 3};
var prevClubs = from player in players
where player.previousClubs.Any(m => clubIds.Contains(m.ID))
select new HistoryOfPlayer {
Player = player,
Clubs = player.previousClubs
.Where(m => clubIds.Contains(m.ID))
.Select(c => c.Name)
};
在svik之后编辑他的评论:
List<int> clubIds = new List<int> { 1, 2, 3};
var prevClubs = from player in players
where clubIds.All(id => player.previousClubs
.select(club => club.ID)
.contains(id))
select new HistoryOfPlayer {
Player = player,
Clubs = player.previousClubs
.Where(m => clubIds.Contains(m.ID))
.Select(c => c.Name)
};
*注意这是在没有IDE的情况下编写的,所以我没有检查它是否有效。