Intersect lists on KeyValuePair key?

 

Questions


How do I insertsect two lists of KeyValuePairs based on their keys? I have 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);

Which expectedly doesn’t work. Do I need to write my own comparer based on the key or is there a easy way using LINQ/Lambda?

Thanks!

 

 

————————————————-

Answer

var keysFromB = new HashSet<string>(listB.Select(x => x.Key));
var result = listA.Where(x => keysFromB.Remove(x.Key));

Note that this code mimics the behaviour of Intersect by using the Remove method. This means that both sequences are treated as sets: if there are multiple items with the same key in listA then result will only contain one of those items. If you don’t want this behaviour then use the Contains method instead of Remove.

c#,lambda,linq,list

[], [], [], []

Facebook Comments

Post a comment