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.
Mmm, I don't know which is more per formant, but how is your solution not readable?
Whats wrong with
foreach (string key in d1.Keys)
{
d3.Add(key,d1[key]+d2[key]);
}
?
I actually think its more clear than some of the linq solutions. Even though I haven't tested it, I think it could have better performance, since it only enumerates the keys in one dictionary and not the values, you'd use the actual hashing (or whatever is the underlying implementation of the dictionary) to find the values, which is the fastest way to get them.
EDIT:
for the solution where keys wouldnt always be the same, if you only want to get shared ones,you only need to add a line;
foreach (string key in d1.Keys)
{
if(d2.ContainsKey(key)
d3.Add(key,d1[key]+d2[key]);
}
EDIT2:
In order to get all keys/values if they are not the same, then it'd be like this:
foreach (string key in d1.Keys)
{
if(d2.ContainsKey(key)
d3.Add(key,d1[key]+d2[key]);
else
d3.Add(key,d1[key])
}
foreach (string key in d2.keys)
{
if(!d1.ContainsKey(key) // only get keys that are unique to d2
d3.Add(key,d2[key]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With