【发布时间】:2014-02-11 15:46:25
【问题描述】:
我有两个字典,一个包含原始数据,另一个包含新数据。我想比较两个字典并返回一个字典并返回第三个包含更新的字典。
Dictionary<int, Dictionary<string, string>> OriginalDictionary = new Dictionary
{
{1, new Dictionary<string, string>
{{"name", "adam"},
{"age", "15"}
{"occupation", "student"}},
{2, new Dictionary<string, string>
{{"name", "bob"},
{"age", "40"}
{"occupation", "doctor"}},
{3, new Dictionary<string, string>
{{"name", "cameron"},
{"age", "32"}
{"occupation", "teacher"}},
}
Dictionary<int, Dictionary<string, string>> NewDictionary = new Dictionary
{
{1, new Dictionary<string, string>
{{"name", "adam"},
{"age", "15"}
{"occupation", "student"}},
{2, new Dictionary<string, string>
{{"name", "bob"},
{"age", "40"}
{"occupation", "lawyer"}}, //this is where it's different
{3, new Dictionary<string, string>
{{"name", "cameron"},
{"age", "32"}
{"occupation", "teacher"}},
}
我想获取包含更新的第三个字典。它可以是整个第一层,也可以分解成第二层。以下 2 个示例都适用于我。
Dictionary<int, Dictionary<string, string>> UpdateDictionary1 = new Dictionary
{
{2, new Dictionary<string, string>
{{"name", "bob"},
{"age", "40"}
{"occupation", "lawyer"}} //this is where it's different
}
Dictionary<int, Dictionary<string, string>> UpdateDictionary2 = new Dictionary
{
{2, new Dictionary<string, string>
{{"occupation", "lawyer"}}
}
我已经尝试了这篇帖子How to compare two Dictionaries in C# 的答案,但我为 UpdateDictionary 获得的结果仍然包含来自 NewDictionary 的所有数据。 UpdatesDictionary.Count == 3,我的预期输出应该是UpdatesDictionary.Count == 1。我尝试了Where 答案和Except 答案,但它们都没有按我希望的那样工作。
UpdateDictionary = OriginalDictionary.Where(entry => NewDictionary[entry.Key] != entry.Value).ToDictionary(entry => entry.Key, entry => entry.Value);
UpdateDictionary = OriginalDictionary.Except(NewDictionary).ToDictionary(x => x.Key, x => x.Value);
我还有其他方法可以解决这个问题吗?
谢谢!
【问题讨论】:
标签: c# dictionary compare where except