字典< string,int>之间的C#比较和输入的值 [英] C# Comparaison between Dictionary<string, int> and value in enter

查看:66
本文介绍了字典< string,int>之间的C#比较和输入的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数可以将多个字符串关联到int:

I have a function for stock many string associate to 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
}

所以我尝试比较enter接收的字符串和字典中返回return int的字符串之间的比较.

So i try to do a comparaison between string receive in enter and string in my dictionary for return associate int.

有什么主意吗?

感谢您的帮助!

推荐答案

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

You can use ContainsKey() method of Dictionary to check if the key is present in 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
}

这篇关于字典&lt; string,int&gt;之间的C#比较和输入的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆