如何使用字典值获取字典键?
当使用密钥获取值时,如下所示:
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的原因).
Joh*_*ner 21
蛮力.
int key = dic.Where(kvp => kvp.Value == "a").Select(kvp => kvp.Key).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
Zai*_*ikh 10
您还可以使用以下扩展方法按值从字典中获取密钥
Run Code Online (Sandbox Code Playgroud)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; } }
用法也很简单
int key = 0;
if (myDictionary.TryGetKey("twitter", out key))
{
// successfully got the key :)
}
Run Code Online (Sandbox Code Playgroud)