Mayou
Mayou

Reputation: 8828

Merging dictionaries with similar keys but distinct values in C#

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.

Upvotes: 4

Views: 642

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500775

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.

Upvotes: 12

Related Questions