Reputation: 22380
I have two collections
List<CustomClass1> items1
List<CustomClass2> items2
CustomClass1 has a property KEY
CustomClass2 has a property KEY
i want to keep only those entries in items1 which have a matching key in items2. How can this be achieved through LINQ?
thanks
Upvotes: 3
Views: 82
Reputation: 7288
You could always use the Intersect operator-
var result = item1.Intersect(item2);
If necessary the overload allows an equity comparer, although if your items are from the same context it shouldn't be necessary
Upvotes: 0
Reputation: 17808
var q = from i1 in items1
join i2 in items2 on i1.Key equals i2.Key
select i1;
Upvotes: 2
Reputation: 61427
var res = items1.Join(items2,
item1 => item1.Key,
item2 => item2.Key,
(item1, item2) => item1);
Upvotes: 4