问题描述
我的问题已被标记为这个问题的可能重复:中添加2个字典内容而不循环
My question has been flagged as a possible duplicate of this question: How to add 2 Dictionary contents without looping in c#
我相信我的问题是不同的,因为我正在问如何组合两个字典以特定的方式:我想要Dictionary1中的所有项目以及Dictionary2中不存在的所有项目(即密钥不存在)。
I believe my question is different because I am asking how to combine two dictionaries in a particular way: I want all items from Dictionary1 plus all items from Dictionary2 that are not in (ie the key does not exist) in Dictionary1.
我有两个字典像这样:
var d1 = new Dictionary<string,object>();
var d2 = new Dictionary<string,object>();
d1["a"] = 1;
d1["b"] = 2;
d1["c"] = 3;
d2["a"] = 11;
d2["e"] = 12;
d2["c"] = 13;
我想将它们组合成一个新的字典(在技术上,它不一定是一个字典,它可能只是一个 KeyValuePairs
的序列),使得输出包含d1中的所有 KeyValuePairs
,只有来自 d2
的KeyValue对,其键不会出现在 d1
中。
I would like to combine them into a new Dictionary (technically, it does not have to be a dictionary, it could just be a sequence of KeyValuePairs
) such that the output contains all of the KeyValuePairs
from d1 and only the KeyValuePairs from d2
whose Key does not appear in d1
.
概念:
var d3 = d1.Concat(d2.Except(d1))
但是,这是给我所有从d1和d2的元素。
But that is giving me all of the elements from d1 and d2.
似乎应该是很明显的,但是我一定是缺少一些东西。
Seems like it should be obvious, but I must be missing something.
推荐答案
使用 / code>默认情况下,它使用默认的相等性比较器,对于
KeyValuePair
类型比较键和值。您可以这样做:
When you use Except
by default it uses the default equality comparer, which for the KeyValuePair
type compares both the keys and the values. You could this approach instead:
var d3 = d1.Concat(d2.Where(kvp => !d1.ContainsKey(kvp.Key)));
这篇关于将两个字典与LINQ结合在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!