C#字典与lt;字符串,int>;和输入值
我有一个函数,用于将许多字符串关联到int:C#字典与lt;字符串,int>;和输入值,c#,string,dictionary,compare,C#,String,Dictionary,Compare,我有一个函数,用于将许多字符串关联到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
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
}
public int Scale(字符串值)
{
this.stringToInt=新字典()
{
{“1p”,00},{“2p”,01},{“3p”,03}…{“300p”,40}
};
//在这里,我尝试这样做:if(value==(字典中的字符串)返回associateint
}
所以我尝试在enter中的字符串receive和字典中的字符串returnassociateint之间进行比较
有什么想法吗
谢谢您的帮助!您可以使用
字典的ContainsKey()
方法检查字典中是否存在密钥:
if (this.stringToInt.ContainsKey(value)
{
return this.stringToInt[value];
}
else
{
// return something else
}
另一种方法是使用TryGetValue()
:
你在问什么?如果没有匹配的int
,应该返回什么?为什么Scale
的返回类型是int
?@GuruStron这是个错误,我编辑了它。
var valueGot = this.stringToInt.TryGetValue(value, out var associate);
if (valueGot)
{
return associate;
}
else
{
// return something else
}