和输入值,c#,string,dictionary,compare"/>

首页 > 解决方案 > C# 字典之间的比较和输入值

问题描述

我有一个与 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
}

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

任何想法?

谢谢你的帮助!

标签: c#stringdictionarycompare

解决方案


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

if (this.stringToInt.ContainsKey(value)
{
    return this.stringToInt[value];
}
else 
{
    // return something else
}

另一种方法是使用TryGetValue()

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

if (valueGot)
{
    return associate;
}
else 
{
    // return something else
}

推荐阅读