Search code examples
c#linqlistwhere-in

c# where in with list and linq


I have two lists, one have a list of object A an other a list of objects B, like this:

ObjectA
{
    Int64 idObjectA;
    String name;
    ....
}

ObjectB
{
    Int64 idObjectB;
    Int64 idObjectA;
    String name;
    ....
}

I have two list, one with Object A and other with Object B. I want to create a new list C that have only objects B, which IDObjectA is any ID of the list A.

In SQL it would be somthing line that:

select * from B where IDObjectA IN(1,2,3,4...);

In my case, the list of values for the IN clause is the list of ObjectA, which have the property idObjectA.


Solution

  • The same with Join and without Contains:

    var listC = listB.Join(listA, b => b.ObjectAId, a => a.Id, (b, a) => b).ToList();