使用字典值获取字典键

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

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

Dictionary dic = new Dictionary(); dic.Add(1, "a"); Console.WriteLine(dic[1]); Console.ReadLine(); 

如何做相反的事情?

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

你可以反过来使用LINQ:

 var keysWithMatchingValues = dic.Where(p => p.Value == "a").Select(p => p.Key); foreach(var key in keysWithMatchingValues) Console.WriteLine(key); 

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

蛮力。

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

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

 public static class Extensions { public static bool TryGetKey(this IDictionary 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 :) } 

获得一把钥匙的简便方法:

  public static TKey GetKey(Dictionary dictionary, TValue Value) { List KeyList = new List(dictionary.Keys); foreach (TKey key in KeyList) if (dictionary[key].Equals(Value)) return key; throw new KeyNotFoundException(); } 

和多个键:

  public static TKey[] GetKeys(Dictionary dictionary, TValue Value) { List KeyList = new List(dictionary.Keys); List FoundKeys = new List(); foreach (TKey key in KeyList) if (dictionary[key].Equals(Value)) FoundKeys.Add(key); if (FoundKeys.Count > 0) return FoundKeys.ToArray(); throw new KeyNotFoundException(); } 

我意识到这是一个古老的问题,但想要添加一些我想到的东西。

如果你知道一个值只有一个键,你必须通过值和键来查找; 你可以创建两个单独的词典。 一个以原始键为键,值为值,第二个以键为值,值为键。

现在是关于这一点的附注; 它确实耗尽了更多的机器资源,但我猜它比通过LINQ和foreach强制执行更快。