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

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

    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]);
           }
    

提交回复
热议问题