我的dbml文件中有以下3个类:
public class Player {
public int PlayerID {get; set;}
public string Name {get; set;}
}
public class PlayerItem {
public int PlayerItemID {get; set;}
public int PlayerID {get; set;}
public int ItemID {get; set;}
}
在Player.ID和PlayerItem.PlayerID
之间创建了一个关联Public Class CustomItem {
public int ItemID {get; set;}
public string ItemName {get; set;}
}
以下是设置:
<Player>
<Item>
如何只选择那些在PlayerItem列表中至少有一个自定义项目的玩家?这基本上匹配每个玩家的PlayerItems中的ItemID和Item CustomItem中的ID。
最终,我希望有一个简单的玩家列表 - 列出<Player>
- 来使用。
答案 0 :(得分:6)
LINQ让这件事变得简单:
players.Where( p => p.PlayerItemList.Any(
pi => customItems.Any( ci => ci.ItemID == pi.ItemID ) );
这也可以用查询形式编写:
var result = from p in players
from pi in p.PlayerItemList
where customItems.Any( ci => ci.ItemID == pi.ItemID ) );
如果您从自定义项目集创建查找表或词典,则效果最佳:
var customItemDict = customItems.ToDictionary( ci => ci.ItemID );
var result = from p in players
from pi in p.PlayerItemList
where customItemDict.ContainsKey( pi.ItemID ) );