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

后端 未结 6 1254
野性不改
野性不改 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

    What about something like this?

    var fooBar = foo.Keys
        .Union(bar.Keys)
        .Select(
            key => {
                int fval = 0, bval = 0;
    
                foo.TryGetValue(key, out fval);
                bar.TryGetValue(key, out bval);
    
                return new KeyValuePair(key, fval + bval);
            }
        )
        .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
    

    At least it's (kind of?) neat.

提交回复
热议问题