简体   繁体   中英

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

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
}

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

Any idea?

Thanks you for help !

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
}

Another way is to use TryGetValue() :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM