26

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?

recursive
  • 83,943
  • 34
  • 151
  • 241
Rye
  • 2,273
  • 9
  • 34
  • 43
  • possible duplicate of [Getting key of value of a generic Dictionary?](http://stackoverflow.com/questions/255341/getting-key-of-value-of-a-generic-dictionary) – bluish Oct 16 '14 at 15:45

5 Answers5

65

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
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 2
    ack, beat me by 35 seconds! :) – John Gardner Oct 23 '10 at 00:53
  • I'm going to guess that this is probably faster than a for each through keyvaluepairs but isn't faster than reversing the dictionary around huh? I'll have to bench it myself just to see out of curiosity but it would be faster just making the dictionary different right? – user99999991 Mar 10 '14 at 21:31
  • 1
    @user999999928 This is basically the same as doing a foreach though the dictionary. If you are going to be doing a lot of lookups, building a "reversed" dictionary (which requires a collection for value) would make lookups faster, but insertions/changes would need to be handled in both. – Reed Copsey Mar 10 '14 at 21:37
  • I get a `.Where` doesnt exist for Dictionary – Si8 Apr 02 '19 at 18:21
21

Brute force.

        int key = dic.Where(kvp => kvp.Value == "a").Select(kvp => kvp.Key).FirstOrDefault();
John Gardner
  • 24,225
  • 5
  • 58
  • 76
10

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
  • 6,013
  • 6
  • 41
  • 66
3

easy way for get one key:

    public static TKey GetKey<TKey,TValue>(Dictionary<TKey, TValue> dictionary, TValue Value)
    {
        List<TKey> KeyList = new List<TKey>(dictionary.Keys);
        foreach (TKey key in KeyList)
            if (dictionary[key].Equals(Value))
                return key;
        throw new KeyNotFoundException();
    }

and for multiples keys:

    public static TKey[] GetKeys<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TValue Value)
    {
        List<TKey> KeyList = new List<TKey>(dictionary.Keys);
        List<TKey> FoundKeys = new List<TKey>();
        foreach (TKey key in KeyList)
            if (dictionary[key].Equals(Value))
                FoundKeys.Add(key);
        if (FoundKeys.Count > 0)
            return FoundKeys.ToArray();
        throw new KeyNotFoundException();
    }
TSnake41
  • 405
  • 3
  • 8
0

I realize this is an old question but wanted to add something I thought of.

If you know there will be only one key to one value and you'll have to look up via value as well as key; you can create two separate dictionaries. One with the original key as the key and value as the value and the second with the key as the value and value as the key.

Now a side note about this; it does use up more machine resources but I'm guessing it's faster then brute forcing through LINQ and foreach.

Naate
  • 115
  • 10
  • 1
    I was thinking about the same. The values need to be unique of course. I think it depends how many times you need to look up values. If this is often (10+ times), it is probably worth it. – Leo Muller May 15 '18 at 08:09