how to do a dictionary reverse lookup

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.


1) Keys are unique, values are not. For a given value you have a set of keys.

2) Lookup by key is O(log n). Iterating with foreach or LINQ is O(n).

So,
Option A: Iterate with LINQ, spend O(n) per request, no additional memory.
Option B: Maintain Dictionary<ValueType, HashSet<KeyType>>, spend O(log n) per request, use O(n) additional memory. (There are two suboptions: build this dictionary before a series of look-ups; maintain it all the time)


How about using the linq function ToDictionary:

var reversedDictionary = dictionary.ToDictionary(x => x.Value, x => x.Key);

Use the Linq ToDictionary function:

var reversed = d.ToDictionary(x => x.Value, x => x.Key);

You can see below that it works, as tested in Linqpad:

var d = new Dictionary<int, string>();
d.Add(1,"one");
d.Add(2,"two");
d.Dump(); //prints it out in linq-pad
var reversed = d.ToDictionary(x => x.Value, x => x.Key);
reversed.Dump(); //prints it out in linq-pad

Prints

Tags:

C#