简体   繁体   English

C# 字典之间的比较<string, int>和输入值</string,>

[英]C# Comparaison between Dictionary<string, int> and value in enter

I have a function for stock many string associate to int:我有一个 function 用于库存许多与 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
}

So i try to do a comparaison between string receive in enter and string in my dictionary for return associate int.所以我尝试在输入中的字符串接收和我的字典中的字符串之间进行比较,以返回关联 int。

Any idea?任何想法?

Thanks you for help !谢谢你的帮助!

You can use ContainsKey() method of Dictionary to check if the key is present in dictionary:您可以使用DictionaryContainsKey()方法来检查键是否存在于字典中:

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

Another way is to use TryGetValue() :另一种方法是使用TryGetValue()

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 字典输出之间的差异 <int, string> 和队列 <KeyValuePair<int, string> &gt;在C#中 - Discrepancies between output of Dictionary<int, string> and Queue<KeyValuePair<int, string>> in C# 字典 <string, int> 列出 <Dictionary<string, int> &gt;在C#中 - Dictionary<string, int> to List<Dictionary<string, int>> in c# 嵌套字典中的C#值总和,其中value是一个类Dictionary <string, Dictionary<Int16, CommonData> &gt; - C# Sum of Values in a nested dictionary where value is a class Dictionary<string, Dictionary<Int16, CommonData>> 使用int和string将数组转换为字典c# - convert array to dictionary c# with int and string 浏览字典<string,int> c# - Navigate through dictionary <string, int> c# c# 更新列表中的值<int>那是在字典里面<string, list<int> &gt; 使用 Lambda</string,></int> - c# updating a value inside a List<int> thats inside a dictionary<string, List<int>> using Lambda 合并 <int, string> 和 <int, double> 成 <double,string> C#字典 - Merge <int, string> and <int, double> into <double,string> C# dictionary C#将JSON反序列化为字典 <int,Tuple<string,int> &gt; - C# deserializing JSON to Dictionary<int,Tuple<string,int>> 定义一个C#类,它有时会在int和字典之间变化 - Defining a C# class that varies sometimes between int and a dictionary 在字符串C#中提取2个int值? - Extract 2 int value inside a string C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM