c#获取两个词典中没有匹配值的所有键

时间:2017-01-05 09:56:04

标签: c# linq

比较两个词典并获取两个词典中存在的所有“键”,但使用linq具有不同的“值” 例如。

var dictionary1 = new Dictionary<string, string>
{
    {"a", "1"},
    {"b", "2"},
    {"c", "3"}
};

var dictionary2 = new Dictionary<string, string>
{
    {"a", "1"},
    {"b", "22"},
    {"c", "33"}
};

output should be 
var DictionaryItems=new Dictionary<string, string>
{
    {"b", "2"},
    {"c", "3"}
};

这里的密钥b有一个二合一和22个第二个字典

1 个答案:

答案 0 :(得分:2)

假设您的密钥是字符串,这里是一个完整的,可工作的,可复制粘贴的示例。

var dictionary1 = new Dictionary<string, string>
{
    {"a", "1"},
    {"b", "2"},
    {"c", "3"}
};

var dictionary2 = new Dictionary<string, string>
{
    {"a", "1"},
    {"b", "22"},
    {"c", "33"}
};

var result = dictionary1
    .Where(d => dictionary2.ContainsKey(d.Key) && dictionary2[d.Key] != d.Value);

这将返回以下内容

enter image description here

如果你只想要不同的键,你可以

var result = dictionary1
  .Where(d => dictionary2.ContainsKey(d.Key) && dictionary2[d.Key] != d.Value)  
  .Select(d=> d.Key);

现在将返回

enter image description here