Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging dictionaries with similar keys but distinct values in C#

Tags:

c#

dictionary

Consider the following dictionaries:

Dictionary<string, double> dict1 = new Dictionary<string, double>()
Dictionary<string, double> dict2 = new Dictionary<string, double>()

The two dictionaries have the exact same keys, but the values are different. I would like to merge the two dictionaries the following way: Create a new dictionary with the same keys as dict1 and dict2, and where the value is an array composed of the matching value in dict1, and the matching value in dict2, for each key.

I can easily do that in a loop, but I was hoping there is a more efficient way of doing it.

Any help would be appreciated! Thank you!

like image 984
Mayou Avatar asked Dec 16 '22 02:12

Mayou


1 Answers

This assumes they really do have the same keys:

var merged = dict1.ToDictionary(pair => pair.Key,
                                pair => new[] { pair.Value, dict2[pair.Key] });

Or to create a Dictionary<string, Tuple<double, double>>

var merged = dict1.ToDictionary(pair => pair.Key,
                                pair => Tuple.Create(pair.Value, dict2[pair.Key]));

Or using an anonymous type to make it cleaner if you're going to use it inside the same method:

var merged = dict1.ToDictionary(pair => pair.Key,
                                pair => new { First = pair.Value,
                                              Second = dict2[pair.Key]) });

As noted in comments, these all still loop internally - they won't be more efficient than writing the loop yourself, but it's nicer to read.

like image 110
Jon Skeet Avatar answered May 10 '23 04:05

Jon Skeet