合并字典在关键水平,然后在价值水平 [英] Merging dictionaries in key level and then in value level
问题描述
我有两个字典,如
Dictionary<String, String> one = new Dictionary<string, string>
{
{ "A", "1" },
{ "B", "2" },
{ "C", "3" },
{ "D", "4" },
{ "E", "5" },
{ "F", "6" },
{ "G", "7" },
{ "H", "8" }
};
Dictionary<String, String> two = new Dictionary<string, string>
{
{ "A", "1" },
{ "B", "2" },
{ "C", "3" },
{ "E", "4" },
{ "F", "4" },
{ "I", "6" },
{ "J", "10" },
{ "K", "11" }
};
我需要在关键级别合并两个字典,然后在值级别中并添加生成的字典进入新字典三
,结果字典不应该有相同的键或相同的值,在这种情况下,生成的字典就像
i need to merge the two dictionary in key level and then in value level and to add the resulting dictionary into the new dictionary three
, the resulting dictionary should not have same keys or same values and in this case the resulting dictionary is like
Dictionary<String, String> three = new Dictionary<string, string>
{
{ "A", "1" },
{ "B", "2" },
{ "C", "3" },
{ "D", "4" },
{ "E", "5" },
{ "F", "6" },
{ "G", "7" },
{ "H", "8" },
{ "J", "10" },
{ "K", "11" }
};
现在我正在使用像
- 联合两个字典中的所有键
- 使用新的键创建新字典
- 删除重复值相同的值)
编辑:如果这两个字典具有相同的键值对,那么我需要存储来自第一个字典的键值对。
EDIT: if both the dictionaries having same key value pair then i need to store the the key value pair from the first dictionary .
有没有办法使用LINQ?
提前感谢
is there any way to do this using LINQ? Thanks in advance
推荐答案
一个选项,使用字典是键/值对序列的事实:
One option, using the fact that a dictionary is a sequence of key/value pairs:
var dictionary = dictionary1.Concat(dictionary2)
.ToLookup(pair => pair.Key, pair => pair.Value)
.ToDictionary(x => x.Key, x => x.First());
将工作。
That's not terribly efficient, admittedly (as it essentially builds up a hash table twice) but I believe it will work.
这篇关于合并字典在关键水平,然后在价值水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!