tags:

views:

66

answers:

4

How to get the dictionary key by using the dictionary value?

when getting the value using the key its like this:

Dictionary<int, string> dic = new Dictionary<int, string>();

dic.Add(1, "a");

Console.WriteLine(dic[1]);
Console.ReadLine();

How to do the opposite?

+7  A: 

A dictionary is really intended for one way lookup from Key->Value.

You can do the opposite use LINQ:

var keysWithMatchingValues = dic.Where(p => p.Value == "a").Select(p => p.Key);

foreach(var key in keysWithMatchingValues)
    Console.WriteLine(key);

Realize that there may be multiple keys with the same value, so any proper search will return a collection of keys (which is why the foreach exists above).

Reed Copsey
ack, beat me by 35 seconds! :)
John Gardner
+2  A: 

Brute force.

        int key = dic.Where(kvp => kvp.Value == "a").Select(kvp => kvp.Key).FirstOrDefault();
John Gardner
A: 

Here's a post that explains what you need: http://shemesh.wordpress.com/2010/01/22/c-dictionary-get-key-from-value/

Nicolas Bottarini
+1  A: 

You can also use the following extension method to get key from dictionary by value

public static class Extensions
{
    public static bool TryGetKey<K, V>(this IDictionary<K, V> instance, V value, out K key)
    {
        foreach (var entry in instance)
        {
            if (!entry.Value.Equals(value))
            {
                continue;
            }
            key = entry.Key;
            return true;
        }
        key = default(K);
        return false;
    }
}

the usage is also so simple

int key = 0;
if (myDictionary.TryGetKey("twitter", out key))
{
    // successfully got the key :)
}
Zain Shaikh