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

0 votes
asked Jun 3, 2010 by code4life

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?


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


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

4 Answers

0 votes
answered Jun 3, 2010 by driis

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.

.ToLookup(kp => kp.Value)
.ToDictionary(g => g.Key, g => g.First().Key);
0 votes
answered Jun 3, 2010 by giorgi

Here you are:

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

0 votes
answered Jun 3, 2010 by voodoochild

I agree with the answers provided, however you should consider and make the change in your program to actually set up with the <key, value> instead of making this change after.

0 votes
answered Jan 5, 2014 by tormod

Is there a particular context in the application where you have 1-to-1 relation or is it global? If the latter, you may want to check out a BiDirectional Dictionary.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter