Search code examples
c#dictionarygeneric-collections

Comparing dictionaries and creating new dictionary with values in C#


I have two dictionaries Dic A & Dic B. Dic A & Dic B have same keys . I would like to move the values in both the dictionaries into a new dictionary (with Value from Dic A being the key in new dictionary). I couldnt figure out a way in merging or intersecting the two dictionaries to get a new one. What would be the right approach in getting the desired output

Dic A
=======

A1   Val 1
A2   Val 2
A3   Val 3

Dic B
========

A1  Cat 1
A2  Cat 2 
A3  Cat 3

Desired Result

Dic C
=======

Val 1  Cat 1 
Val 2  Cat 2 
Val 3  Cat 3

Solution

  • That sounds like a join on the two original ones, followed by a conversion:

    var merged = dicA.Join(dicB, pair => pair.Key, pair => pair.Key,
                           (a, b) => new { Key = a.Value, Value = b.Value })
                     .ToDictionary(pair => pair.Key, pair => pair.Value);