将两个字典使用LINQ [英] Combine two Dictionaries with linq
问题描述
我有两本词典是这样的:
I have two dictionaries like this:
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
的序列),使得输出包含了所有的 KeyValuePairs
从D1只有从 D 2
的KeyValuePairs其键没有出现在 D 1
。
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.
推荐答案
在使用除了
默认情况下它使用默认的相等比较,这对于 KeyValuePair </ code>类型比较两个键和值。你可以这个方法来代替:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!