Question

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.

Was it helpful?

Solution

var result = from o in objList where intList.Contains(o.ID) select o

OTHER TIPS

using System.Linq;

objList.Where(x => intList.Contains(x.id));

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

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".

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;

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top