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

Posted by George Stocker on Stack Overflow See other posts from Stack Overflow or by George Stocker
Published on 2010-05-11T16:35:34Z Indexed on 2010/05/11 16:54 UTC
Read the original article Hit count: 232

Filed under:
|
|
|
|

I have two dictionaries with the same structure:

Dictionary<string, int> foo = new Dictionary<string, int>() 
{
    {"Table", 5 },
    {"Chair", 3 },
    {"Couch", 1 }
};

Dictionary<string, int> bar = new Dictionary<string, int>() 
{
    {"Table", 4 },
    {"Chair", 7 },
    {"Couch", 8 }
};

I'd like to sum the values of the dictionaries together and return a third dictionaries with the keys, and the total values for each key:

Table, 9
Chair, 10
Couch, 9

My current solution is to loop through the dictionary and pull them out that way, but I know that solution isn't the most performant or most readable. However, I'm hitting a brick wall trying to come up with a solution in LINQ.

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about sum