Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 892
donstack Avatar asked Apr 02 '13 16:04

donstack


People also ask

How do you check if a list contains items from another list?

There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.

How do you check if a list is a subset of another list C#?

You can simply check to see that the set difference between query2 and query1 is the empty set: var isSubset = ! query2. Except(query1).


2 Answers

ListA.Where(a => ListX.Any(x => x.b == a.b)) 
like image 185
Adrian Godong Avatar answered Sep 22 '22 20:09

Adrian Godong


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.

like image 42
Servy Avatar answered Sep 20 '22 20:09

Servy