views:

39

answers:

1

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 setup:

  1. I have a list of Players - List<Player>
  2. Each player has a Entityset child of type PlayerItem
  3. I have a list of Items - List<Item>

How can I select only those players that have at least one custom item in their list of PlayerItems? This is basically matching ItemID in each Player's PlayerItems with the Item ID in CustomItem.

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

+4  A: 

LINQ make this sort of thing easy:

players.Where( p => p.PlayerItemList.Any( 
              pi => customItems.Any( ci => ci.ItemID == pi.ItemID ) );

This can also be written in query form:

var result = from p in players
             from pi in p.PlayerItemList
             where customItems.Any( ci => ci.ItemID == pi.ItemID ) );

This will perform best if you create a lookup table or dictionary from your custom item set:

var customItemDict = customItems.ToDictionary( ci => ci.ItemID );
var result = from p in players
             from pi in p.PlayerItemList
             where customItemDict.ContainsKey( pi.ItemID ) );
LBushkin
Interesting. I'll give this a shot now.
Alexander Voglund
Make sure you import System.Linq in the namespaces you're using.
LBushkin
Thanks but I'm still having problems. My question was not accurately worded but I have since updated it. I do NOT have a list of PlayerItem. I have a Player object (generated in my dbml file) that has an association to PlayerItem. I'm trying to query but I cannot query p.PlayerItems as it is an Entityset and throwing errors in Visual Studiu.
Alexander Voglund
You are correct in both cases :-) However it wasn't a reference to System.Linq but Systen.DATA.linq that resolved everything. Thanks!
Alexander Voglund