Filter the list of objects compared to another list of different objects

I have the following 3 classes in my dbml file:

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

There is an association created between Player.ID and PlayerItem.PlayerID

Public Class CustomItem {
    public int ItemID {get; set;}
    public string ItemName {get; set;}
}

Here's the setting:

  • I have a list of players - List <Player>
  • Each player has a child Entityset of type PlayerItem
  • I have a list of Items - List <Item>

How to select only those players who have at least one user item in the PlayerItems list? This basically matches the ItemID in each Player PlayerItems with the ID element in CustomItem.

Ultimately, I would like to have a simple list of players - List <Player>- to work with.

+5
source share
1 answer

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 ) );
+6

All Articles