Rye
Rye

Reputation: 2311

Get Dictionary key by using the dictionary value

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?

Upvotes: 26

Views: 77248

Answers (5)

Naate
Naate

Reputation: 125

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.

Upvotes: 1

TSnake41
TSnake41

Reputation: 405

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();
    }

Upvotes: 3

Zain Shaikh
Zain Shaikh

Reputation: 6043

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 :)
}

Upvotes: 10

John Gardner
John Gardner

Reputation: 25156

Brute force.

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

Upvotes: 21

Reed Copsey
Reed Copsey

Reputation: 564861

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).

Upvotes: 65

Related Questions