简体   繁体   中英

Merge <int, string> and <int, double> into <double,string> C# dictionary

If my dictionary 1 is :

0 : string1
1 : string2
2 : string3

And my dictionary 2 is :

0 : 28.0
1 : 12.6
2 : -12.4

How do I get a combined dictionary with :

28.0  : string1
12.6  : string2
-12.4 : string3

This is how I have used them so far

SortedDictionary<int, double> map2 = new SortedDictionary<int, double>();
SortedDictionary<int, string> map1 = new SortedDictionary<int, string>();

Edit - For this question, assume the keys in both the dictionaries are sequential and in increasing order and always the same.

Assuming both dictionaries have the same count and have the same keys:

map1.ToDictionary(x => map2[x.Key], x => x.Value)

This would fail if the second dictionary has duplicated values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM