How do I sum values from two dictionaries in C#?

后端 未结 6 1252
野性不改
野性不改 2020-12-19 00:51

I have two dictionaries with the same structure:

Dictionary foo = new Dictionary() 
{
    {\"Table\", 5 },
    {\"Chair         


        
6条回答
  •  春和景丽
    2020-12-19 01:18

    If you have a cast iron guarantee that the two sets of keys are the same:

    Dictionary Res2 = foo.ToDictionary(orig => orig.Key, orig => orig.Value + bar[orig.Key]);
    

    Best I could come up with if keys aren't same set:

    var AllKeys = foo.Keys.Union(bar.Keys);
    var res3 = AllKeys.ToDictionary(key => key,  key => (foo.Keys.Contains(key)?foo[key] : 0) + (bar.Keys.Contains(key)?bar[key] : 0));
    

提交回复
热议问题