[英]C# Comparaison between Dictionary<string, int> and value in enter
I have a function for stock many string associate to int:我有一个 function 用于库存许多与 int 相关的字符串:
public int Scale(string value)
{
this.stringToInt = new Dictionary<string, int>()
{
{"1p",00},{"2p",01},{"3p",03} ... {"300p",40}
};
// Here i try to do something like that: if(value == (String in dictionary) return associate int
}
So i try to do a comparaison between string receive in enter and string in my dictionary for return associate int.所以我尝试在输入中的字符串接收和我的字典中的字符串之间进行比较,以返回关联 int。
Any idea?任何想法?
Thanks you for help !谢谢你的帮助!
You can use ContainsKey()
method of Dictionary
to check if the key is present in dictionary:您可以使用
Dictionary
的ContainsKey()
方法来检查键是否存在于字典中:
if (this.stringToInt.ContainsKey(value)
{
return this.stringToInt[value];
}
else
{
// return something else
}
Another way is to use TryGetValue()
:另一种方法是使用
TryGetValue()
:
var valueGot = this.stringToInt.TryGetValue(value, out var associate);
if (valueGot)
{
return associate;
}
else
{
// return something else
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.