在哈希表 C# 中按值获取键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12177596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get key by value in hash table c#
提问by motaz99
I want to get the key of my value but this does not Possible in Hashtable
Is there data stretcher to do this ??
我想获取我的值的键,但这在 Hashtable 中
是不可能的是否有数据拉伸器可以做到这一点?
Hashtable x = new Hashtable();
x.Add("1", "10");
x.Add("2", "20");
x.Add("3", "30");
x.GetKey(20);//equal 2
采纳答案by sloth
If all your keys are strings.
如果你所有的键都是字符串。
var key = x.Keys.OfType<String>().FirstOrDefault(s => x[s] == "20")
or better use a Dictionary instead:
或者更好地使用字典:
Dictionary<string, string> x = new Dictionary<string, string>();
x.Add("1", "10");
x.Add("2", "20");
x.Add("3", "30");
string result = x.Keys.FirstOrDefault(s => x[s] == "20");
If you know that your value will always have just one distinct key, use Singleinstead of FirstOrDefault.
如果您知道您的值将始终只有一个不同的键,请使用Single代替FirstOrDefault。
回答by Aghilas Yakoub
You can use Linq operators
您可以使用 Linq 运算符
x.Keys.OfType<String>().FirstOrDefault(a => x[a] == "20")
You can iterate with foreach
您可以使用 foreach 进行迭代
回答by sundar
If you looking for O(1) solution, then you may need to implement the reversed Hashtableas well where the value of this table will be key and key becomes corresponding value.
如果您正在寻找 O(1) 解决方案,那么您可能还需要实现相反的方法Hashtable,其中该表的值将成为键,而键成为相应的值。
回答by Oliver
I strongly recommend to use two Dictionary<string, string>but this would mean that their is a 1-1 relationship between the items:
我强烈建议使用两个,Dictionary<string, string>但这意味着它们是项目之间的 1-1 关系:
var dict1 = new Dictionary<string, string>();
var dict2 = new Dictionary<string, string>();
dict1.Add("1", "10");
dict2.Add("10", "1");
dict1.Add("2", "20");
dict2.Add("20", "2");
dict1.Add("3", "30");
dict2.Add("30", "3");
var valueOfDictOne = dict1["1"];
var valueOfDictTwo = dict2["10"];

