Combining dictionaries with similar keys, but excellent values ​​in C #

Consider the following dictionaries:

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

Two dictionaries have the same keys, but the meanings are different. I would like to merge two dictionaries as follows: Create a new dictionary with the same keys as dict1and dict2, and where the value is an array consisting of the corresponding value in dict1, and the corresponding value dict2for each key.

I can easily do this in a loop, but I was hoping there was a more efficient way to do this.

Any help would be appreciated! Thanks!

+4
source share
1 answer

This suggests that they really have the same keys:

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

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

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

, , :

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

, - , , .

+12

Source: https://habr.com/ru/post/1523362/