c# - 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。
任何想法?
谢谢你的帮助!
解决方案
您可以使用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
}
推荐阅读
- python - Django获取模型日期字段值
- matplotlib - 使用 Matplotlib 时 Jupyter 笔记本中的条形图和显示问题
- python - 从列标题到列值
- c - 将用户的输入写入二进制文件
- java - 如何通过按键盘上的左右箭头键来更改背景颜色?(不在钟内,在钟外)
- python - 如何在 python3 中转换 php md5(sha1(time()))?
- javascript - react 应用程序刷新后如何从本地存储中强制注销或删除令牌?
- coordinates - 平面切割球体
- rust - Rust 中的“Cell”可以安全地用于“Rc”吗?
- amazon-web-services - 使用 Rundeck 配置 AWS ALB 和 Cognito