开发者

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 开发者_Go百科opposite?


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


Brute force.

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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜