我如何得到一个字典键值在c# ?

Dictionary<string, string> types = new Dictionary<string, string>()
{
    {"1", "one"},
    {"2", "two"},
    {"3", "three"}
};

我想要这样的东西:

getByValueKey(string value);

getByValueKey("one")必须返回"1"。

最好的方法是什么?也许是哈希表或排序列表?


当前回答

Dictionary<K,V>扩展。我已经用了很长时间了::

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

并使用as:

public static void Main()
{
    Dictionary<string, string> dict = new Dictionary<string, string>()
    {
        {"1", "one"},
        {"2", "two"},
        {"3", "three"}
    };
     
     string value="two"; 
     if (dict.TryGetKey(value, out var returnedKey))
         Console.WriteLine($"Found Key {returnedKey}");
     else
         Console.WriteLine($"No key found for value {value}");
}

其他回答

Dictionary<K,V>扩展。我已经用了很长时间了::

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

并使用as:

public static void Main()
{
    Dictionary<string, string> dict = new Dictionary<string, string>()
    {
        {"1", "one"},
        {"2", "two"},
        {"3", "three"}
    };
     
     string value="two"; 
     if (dict.TryGetKey(value, out var returnedKey))
         Console.WriteLine($"Found Key {returnedKey}");
     else
         Console.WriteLine($"No key found for value {value}");
}

我遇到的情况是LINQ绑定不可用,必须显式展开lambda。它的结果是一个简单的函数:

public static T KeyByValue<T, W>(this Dictionary<T, W> dict, W val)
{
    T key = default;
    foreach (KeyValuePair<T, W> pair in dict)
    {
        if (EqualityComparer<W>.Default.Equals(pair.Value, val))
        {
            key = pair.Key;
            break;
        }
    }
    return key;
}

这样称呼它:

public static void Main()
{
    Dictionary<string, string> dict = new Dictionary<string, string>()
    {
        {"1", "one"},
        {"2", "two"},
        {"3", "three"}
    };

    string key = dict.KeyByValue("two");
    Console.WriteLine("Key: " + key);
}

它适用于。net 2.0和其他有限的环境。

public static string GetKeyFromValue(string valueVar)
{
    foreach (string keyVar in dictionaryVar.Keys)
    {
        if (dictionaryVar[keyVar] == valueVar)
        {
            return keyVar;
        }
    }
    return null;
}

其他人可能有更有效的答案,但我个人觉得这个更直观,对我来说很管用。

值不一定是唯一的,所以必须进行查找。你可以这样做:

var myKey = types.FirstOrDefault(x => x.Value == "one").Key;

如果值是唯一的,并且插入的频率低于读取,那么创建一个反向字典,其中值是键,键是值。

你可以这样做:

通过循环遍历字典中的所有KeyValuePair<TKey, TValue>(如果字典中有许多条目,这将是一个相当大的性能打击) 使用两个字典,一个用于值到键映射,一个用于键到值映射(这会占用两倍的内存空间)。

如果不考虑性能,请使用方法1;如果不考虑内存,请使用方法2。

此外,所有键都必须是唯一的,但值不要求是唯一的。您可以有多个具有指定值的键。