Reputation: 41939
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.
Upvotes: 20
Views: 44270
Reputation: 11502
using System.Linq;
objList.Where(x => intList.Contains(x.id));
Upvotes: 15
Reputation: 1
Please note that using the join instead of contains DOES NOT work when the count of items in the list exceeds 49! You will get the error: Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries.
Upvotes: 0
Reputation: 546083
var result = from o in objList where intList.Contains(o.ID) select o
Upvotes: 17
Reputation: 1139
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));
Upvotes: 10
Reputation: 17434
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;
Upvotes: 2
Reputation: 204259
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".
Upvotes: 6