简体   繁体   中英

Get int value from Dictionary<string,string>

I have an AssignApiPollerParameters method which gets Dictionary<string,string> configuration and its ok for my other methods, but I have the method ExtractPollingInterval which returns int.

How can I fix this conflict and get it from dictionary or maybe convert it?

public ApiPollerTemplateParameters AssignApiPollerParameters(Dictionary<string, string> configuration)
{
    return SetBaseProperties<ApiPollerTemplateParameters>(
    new ApiPollerTemplateParameters {PollingInterval = ExtractPollingInterval(configuration)});
}

private static int ExtractPollingInterval(IReadOnlyDictionary<string, string> configuration)
{
    int pollingInterval;
    return configuration.TryGetValue(PollingIntervalProperty, out pollingInterval ) ? pollingInterval : 0;
}

You need to first get the value as a string and convert this to an int. A simple sample is:

private static int ExtractPollingInterval(IReadOnlyDictionary<string, string> configuration)
{
    string pollingInterval;
    return configuration.TryGetValue(PollingIntervalProperty, out pollingInterval) 
      ? int.Parse(pollingInterval) 
      : 0;
}

The code above reads the string from the dictionary and uses int.Parse to read an integer from the string. Please note that int.Parse will throw an error, if the string does not contain a valid integer. This might also depend on regional settings.

In order to cope with invalid values, you can use int.TryParse , eg

private static int ExtractPollingInterval(IReadOnlyDictionary<string, string> configuration)
{
    string pollingIntervalStr;
    if (!configuration.TryGetValue(PollingIntervalProperty, out pollingIntervalStr))
    {
      return 0; // No value provided at all
    }
    // Value provided, but maybe not a valid integer
    return int.TryParse(pollingIntervalStr, out var pollingInterval)
      ? pollingInterval 
      : 0;
}

There are various overloads for int.Parse and int.TryParse that offer parameters for regional settings.

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