按值获取字典键

如何在C#中按值获取字典键?


Dictionary<string, string> types = new Dictionary<string, string>()

{

            {"1", "one"},

            {"2", "two"},

            {"3", "three"}

};

我想要这样的东西:


getByValueKey(string value);

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


最好的方法是什么?也许HashTable,SortedLists?


扬帆大鱼
浏览 473回答 3
3回答

万千封印

您可以这样做:通过遍历KeyValuePair<TKey, TValue>字典中的所有数字(如果您在字典中有许多条目,这将对性能产生很大的影响)使用两个字典,一个用于值到键的映射,另一个用于键到值的映射(这将占用内存的两倍)。如果不考虑性能,则使用方法1;如果不考虑内存,则使用方法2。同样,所有键都必须是唯一的,但是值不必是唯一的。您可能有多个具有指定值的键。有什么原因不能扭转键值关系?

繁华开满天机

我处于无法使用Linq绑定并且必须显式扩展lambda的情况。它产生了一个简单的功能:public static T KeyByValue<T, W>(this Dictionary<T, W> dict, W val){&nbsp; &nbsp; T key = default;&nbsp; &nbsp; foreach (KeyValuePair<T, W> pair in dict)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (EqualityComparer<W>.Default.Equals(pair.Value, val))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key = pair.Key;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return key;}如下调用:public static void Main(){&nbsp; &nbsp; Dictionary<string, string> dict = new Dictionary<string, string>()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; {"1", "one"},&nbsp; &nbsp; &nbsp; &nbsp; {"2", "two"},&nbsp; &nbsp; &nbsp; &nbsp; {"3", "three"}&nbsp; &nbsp; };&nbsp; &nbsp; string key = KeyByValue(dict, "two");&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; Console.WriteLine("Key: " + key);}适用于.NET 2.0和其他受限环境。
打开App,查看更多内容
随时随地看视频慕课网APP