Find items from a list which exist in another list

I have a List<PropA>

PropA  
{  
    int a;  
    int b;  
}

and another List<PropX>

PropX  
{  
    int a;  
    int b;  
}

Now i have to find items from List<PropX> which exist in List<PropA> matching b property using lambda or LINQ.


ListA.Where(a => ListX.Any(x => x.b == a.b))

What you want to do is Join the two sequences. LINQ has a Join operator that does exactly that:

List<PropX> first;
List<PropA> second;

var query = from firstItem in first
    join secondItem in second
    on firstItem.b equals secondItem.b
    select firstItem;

Note that the Join operator in LINQ is also written to perform this operation quite a bit more efficiently than the naive implementations that would do a linear search through the second collection for each item.


var commonNumbers = first.Intersect(second); 

This will give you the common values between two lists, a much faster and cleaner approach than join or other Lambda expressions.

Just try it.

Source : MSDN