Reversing a Dictionary in LINQ and C#

Someone recently gave me the task to figure out how to reverse a dictionary.  Basically they wanted to switch the keys and values so the values become the keys and the keys become the values.  Instead of trying to figure it out myself, I googled reverse dictionary and found it on stackoverflow.  You simply say


var
newDictionary = oldDictionary.ToDictionary(x => x.Value, x => x.Key);

if you think you may have duplicates then use:


var newDictionary = oldDictionary.GroupBy(pair => pair.Value).Select(group => group.First()).ToDictionary(pair => pair.Value, pair => pair.Key);


If you just want to search values linearly to find a key using the value(for smaller dictionaries) use:

var result = (from val in oldDictionary.Keys where valToFind == oldDictionary[val] select val).First();






 
Ebook Download
View all
Learn
View all