How do I sum values from two dictionaries in C#?
- by George Stocker
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.