Farhad-Taran
Farhad-Taran

Reputation: 6512

how to filter two sets of keyvalue pairs for differences using linq?

I have two lists of KeyValue pairs which I want to filter.

I would like to retrieve the keyvalue pairs from list B if the value is different to the key value in list A.

List A      List B 
<a,1>       <b,4>
<b,2>       <c,5>
<c,3>

so if I filter the above two key value pair lists I would get the following:

List c
<b,4>
<c,5>

is this possible without having to use a foreach loop and checking individual key values?

Upvotes: 1

Views: 376

Answers (2)

rdans
rdans

Reputation: 2157

Try something like this:

ListB.Where(kvpB => !ListA.Select(kvpA => kvpA.Value).Contains(kvpB.Value))

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

Join both lists by keys, then select those items, which have different values:

from kvpA in listA
join kvpB in listB on kvpA.Key equals kvpB.Key
where kvpA.Value != kvpB.Value
select kvpB

Lambda syntax:

listA.Join(listB, 
           kvpA => kvpA.Key, 
           kvpB => kvpB.Key, 
           (kvpA, kvpB) => new { kvpA, kvpB })
     .Where(x => x.kvpA.Value != x.kvpB.Value)
     .Select(x => x.kvpB)
     .ToList()

Upvotes: 3

Related Questions