Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 412
George Stocker Avatar asked May 11 '10 16:05

George Stocker


1 Answers

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]);
       }
like image 63
Francisco Noriega Avatar answered Oct 05 '22 09:10

Francisco Noriega