【问题标题】:C# Comparaison between Dictionary<string, int> and value in enterC# 比较 Dictionary<string, int> 和 enter 中的值
【发布时间】:2020-10-14 10:43:23
【问题描述】:

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

有什么想法吗?

感谢您的帮助!

【问题讨论】:

  • 你在问什么? ContainsKey?
  • 如果没有匹配的int应该返回什么?为什么Scale 的返回类型为int
  • @GuruStron 这是一个错误,我编辑了它。

标签: c# string dictionary compare


【解决方案1】:

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

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
}

【讨论】:

    猜你喜欢
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多