C# 比较 Dictionary<string, int> 和 enter 中的值

New*_*ork 3 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(value == (String in dictionary) return associate int
}
Run Code Online (Sandbox Code Playgroud)

因此,我尝试在输入中的字符串接收和字典中的字符串之间进行比较,以返回关联 int。

任何的想法?

谢谢你的帮助!

Rom*_*och 6

您可以使用ContainsKey()方法Dictionary来检查字典中是否存在键:

if (this.stringToInt.ContainsKey(value)
{
    return this.stringToInt[value];
}
else 
{
    // return something else
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用TryGetValue()

var valueGot = this.stringToInt.TryGetValue(value, out var associate);

if (valueGot)
{
    return associate;
}
else 
{
    // return something else
}
Run Code Online (Sandbox Code Playgroud)