views:

6580

answers:

4

I have a List<int> and a List<customObject>. The customObject class has an ID property. How can I get a List<customObject> containing only the objects where the ID property is in the List<int> using LINQ?

Edit: I accepted Konrads answer because it is easier/more intuitive to read.

+3  A: 

Untested, but it'll be something like this:

var matches = from o in objList 
                  join i in intList on o.ID equals i
                  select o;

@Konrad just tested it, and it does work - I just had a typo where I'd written "i.ID" rather than "i".

Matt Hamilton
+5  A: 
var result = from o in objList where intList.Contains(o.ID) select o

/EDIT: bogus.

Konrad Rudolph
+1  A: 

Just for completeness (and maybe it's easier to read?), using a "where" similar to Matt's "join":

var matches = from o in customObjectList
              from i in intList
              where o.ID == i
              select o;
Lucas
+1  A: 

I have had a similar problem just now and used the below solution. If you already have the list of objects you can remove all not found in the int list, leaving just matches in objList.

objList.RemoveAll(x => !intList.Contains(x.id));
Henryk