Home > Mobile >  Get int value from Dictionary<string,string>
Get int value from Dictionary<string,string>

Time:07-30

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;
}

CodePudding user response:

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, e.g.

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.

  • Related