Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ transform Dictionary<key,value> to Dictionary<value,key>

Tags:

c#

linq

I'm having a low-brainwave day... Does anyone know of a quick & elegant way to transform a Dictionary so that the key becomes the value and vice-versa?

Example:

var originalDictionary = new Dictionary<int, string>() {     {1, "One"}, {2, "Two"}, {3, "Three"} }; 

becomes

var newDictionary = new Dictionary<string, int>(); // contents:   // {  //    {"One", 1}, {"Two", 2}, {"Three", 3}  // }; 
like image 547
code4life Avatar asked Jun 03 '10 17:06

code4life


2 Answers

Use ToDictionary ?

orignalDictionary.ToDictionary(kp => kp.Value, kp => kp.Key); 

This works because IDictionary<TKey,TElement>; is also an IEnumerable<KeyValuePair<TKey,TElement>>;. Just be aware that if you have duplicate values, you will get an exception.

In case you have duplicate values, you will need to decide on what to do with them. One simple way would be to ignore duplicates by grouping on Value first, then make the dictionary.

originalDictionary .ToLookup(kp => kp.Value) .ToDictionary(g => g.Key, g => g.First().Key); 
like image 133
driis Avatar answered Oct 26 '22 00:10

driis


Here you are:

var reversed = orignalDictionary.ToDictionary(el => el.Value, el => el.Key);

like image 36
Giorgi Avatar answered Oct 26 '22 00:10

Giorgi