在相交关键KeyValuePair名单? [英] Intersect lists on KeyValuePair key?

查看:100
本文介绍了在相交关键KeyValuePair名单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何insertsect KeyValuePairs的两个名单根据自己的钥匙?我曾尝试:

 列表< KeyValuePair<字符串,字符串>> = listA的新的List< KeyValuePair<字符串,字符串>>(); 
名单,LT; KeyValuePair<字符串,字符串>>数组listB =新的List< KeyValuePair<字符串,字符串>>();
...
VAR的结果= listA.Intersect(数组listB);



这果然是行不通的。我是否需要根据主要写我自己的比较器或有使用LINQ / LAMBDA一个简单的方法?



谢谢!


解决方案

  VAR keysFromB =新的HashSet<串GT;(listB.Select(X => x.Key)); 
VAR的结果= listA.Where(X => keysFromB.Remove(x.Key));

请注意,此代码模仿的 相交 使用的 删除 方法。这意味着两个序列为一组治疗:如果有多个项目使用相同的密钥在为listA 然后结果将只包含这些项目中的一个。如果你不希望这种行为,然后使用 包含 方法,而不是删除


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!

解决方案

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.

这篇关于在相交关键KeyValuePair名单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆