Cross KeyValuePair Key Lists?

How to insert two KeyValuePairs lists based on their keys? I tried:

List<KeyValuePair<string, string>> listA = new List<KeyValuePair<string, string>>();
List<KeyValuePair<string, string>> listB = new List<KeyValuePair<string, string>>();
...
var result = listA.Intersect(listB);

This is not expected to work. Do I need to write my own key-based comparator, or is there an easy way to use LINQ / Lambda?

Thank!

+3
source share
2 answers
var keysFromB = new HashSet<string>(listB.Select(x => x.Key));
var result = listA.Where(x => keysFromB.Remove(x.Key));

Please note that this code reproduces the behavior Intersectwith Remove. This means that both sequences are treated as sets: if listAthere are several elements with the same key, then resultonly one of these elements will be contained. If you do not want this behavior, use Containsinstead Remove.

+7

, - , Intersect.

ProjectionEqualityComparer MiscUtil, :

// Ick what a mouthful
var comparer = ProjectionEqualityComparer<KeyValuePair<string, string>>.Create
       (x => x.Key);

var result = listA.Intersect(listB, comparer);

, :

var commonPairs = from pairA in listA
                  join pairB in listB on pairA.Key equals pairB.Key
                  select new { pairA, pairB };
+5

Source: https://habr.com/ru/post/1764529/


All Articles