stackoverflowuser
stackoverflowuser

Reputation: 22380

LINQ query help

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

Answers (4)

Kelly Robins
Kelly Robins

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

asawyer
asawyer

Reputation: 17808

var q = from i1 in items1 
        join i2 in items2 on i1.Key equals i2.Key 
        select i1;

Upvotes: 2

Femaref
Femaref

Reputation: 61427

var res = items1.Join(items2,
                      item1 => item1.Key, 
                      item2 => item2.Key, 
                      (item1, item2) => item1);

Upvotes: 4

Mo Valipour
Mo Valipour

Reputation: 13486

var res = items1.Where(a=> items2.Any(c=>c.Key == a.Key));

Upvotes: 3

Related Questions