tags:

views:

299

answers:

2

I have 2 a class's:

public class ObjectA
{
    public int Id;
    public string Name;
}

public class ObjectB
{
    public int Id;
    public string Name;
    public List<ObjectA> ListOfObjectA;
}

So I have two lists: One of ObjectB (ListObjectB) and Another contains a list of id's of ObjectA (called ListOfIdsA). If this i want to get a list of ObjectB where ObjectB.ListOfObjectA is in the ListOfIdsA.

My first (and wrong) approach was

ListObjectB.Where(p=> ListOfIdsA.Contains(p.ListOfObjectA.Select(b=>b.Id)))

But this obviously trows an exception. I google it, stackoverflowed, but I'm thinking that my search skills aren't going so well in this, can anybody give a ninja awser of this? (Prefereably in lambda expression)

A: 

If I understand the question correctly, you're looking for Intersect, with your own IEqualityComparer. Remember to correctly implement GetHashCode in the comparer.

SLaks
+9  A: 

Are you trying to get a list of ObjectBs where all of the ObjectAs are in ListOfIdsA, or any of them?

I think you want either:

ListObjectB.Where(p => p.ListOfObjectA.Any(x => ListOfIdsA.Contains(x.Id)))

or

ListObjectB.Where(p => p.ListOfObjectA.All(x => ListOfIdsA.Contains(x.Id)))

(You may well want to make ListOfIdsA a HashSet<string> if it's of significant size, btw.)

Jon Skeet
Learn something new every day...for some reason I was thinking Extension methods were the way to solve this one.
Justin Niessner
I want it any of them. Thx for the prompt response (it was my first question in here, and damn, that was fast!)
Berto
@Justin: Well Where, All and Any *are* extension methods :)
Jon Skeet
@Jon - Doh! Poorly worded comment. I was referring to hand rolling my own Extension Methods.
Justin Niessner
@Justin: Ah - that does indeed make more sense :)
Jon Skeet