使用字典值获取字典键

Rye*_*Rye 25 c# dictionary

如何使用字典值获取字典键?

当使用密钥获取值时,如下所示:

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

dic.Add(1, "a");

Console.WriteLine(dic[1]);
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

如何做相反的事情?

Ree*_*sey 62

字典实际上是用于从Key-> Value进行单向查找.

您可以使用相反的LINQ:

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

foreach(var key in keysWithMatchingValues)
    Console.WriteLine(key);
Run Code Online (Sandbox Code Playgroud)

意识到可能有多个具有相同值的键,因此任何正确的搜索都将返回一组键(这就是上面存在foreach的原因).

  • 确认,打败了我35秒!:) (2认同)

Joh*_*ner 21

蛮力.

        int key = dic.Where(kvp => kvp.Value == "a").Select(kvp => kvp.Key).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

  • int key = dic.FirstOrDefault(kvp => kvp.Value =="a").密钥; (5认同)
  • 但是,如果没有具有该值的键,则会抛出异常.(`FirstOrDefault`返回null,你取'.Key`为null) (2认同)

Zai*_*ikh 10

您还可以使用以下扩展方法按值从字典中获取密钥

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法也很简单

int key = 0;
if (myDictionary.TryGetKey("twitter", out key))
{
    // successfully got the key :)
}
Run Code Online (Sandbox Code Playgroud)