frenchie frenchie - 1 year ago 136
C# Question

how to do a dictionary reverse lookup

I have a dictionary of type

<string, string>
and for a particular case, I need to do a reverse lookup. So for instance suppose I have this entry
<"SomeString", "ab">
and that I pass in
"ab"
then I would like to return
"SomeString"
.
Before I embark on a
foreach
loop over every entry in the dictionary, I was wondering what would be the most efficient way to do this reverse lookup?

Thanks.

Answer Source

Basically, You can use LINQ and get the Key like this, without reversing anything:

var key = dictionary.FirstOrDefault(x => x.Value == "ab").Key;

If you really want to reverse your Dictionary, you can use an extension method like this:

public static Dictionary<TValue, TKey> Reverse<TKey, TValue>(this IDictionary<TKey, TValue> source)
{
     var dictionary = new Dictionary<TValue, TKey>();
     foreach (var entry in source)
     {
         if(!dictionary.ContainsKey(entry.Value))
             dictionary.Add(entry.Value, entry.Key);
     }
     return dictionary;
} 

Then you can use it like this:

var reversedDictionary = dictionary.Reverse();
var key = reversedDictionary["ab"];

Note: if you have duplicate values then this method will add the first Value and ignore the others.