I have two dictionaries, one contains the original data and the other contains the new data. I want to compare the two dictionaries and return a dictionaries and return a third that contains updates.
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"}},
}
I want to get a third dictionary that contains the updates. It can be eithere the whole first level, or breaking down into the second level. The below 2 examples will both work for me.
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"}}
}
I have tried the answers from this post How to compare two Dictionaries in C#, but the results I got for UpdateDictionary still contains all the data from NewDictionary. UpdatesDictionary.Count == 3
, which my expected output should be UpdatesDictionary.Count == 1
. I tried the Where
answer and the Except
answer and they both weren't working as I want it to be.
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);
Is there some other way I should approach this?
Thanks!