views:

97

answers:

3

Hi all

I think it is not complicated but after doing some research I can't find an answer to a simple problem.

I am iterating through keys in a dictionary and I would like to use the key which is a string as a double in some calculation.

If I do this :

foreach (KeyValuePair<string, List<string> price in dictionary)
double ylevel = Convert.ToDouble(price.Key);

It seems to not work and I get a "Input string was not in a correct format" error.

What is the right way to get a double from the key..

Thanks

Bernard

+4  A: 

You're doing it correctly.

The error message indicates that one of your keys is not actually a double.

If you step through this example in a debugger, you'll see it fails on the second item:

var dictionary = new Dictionary<string, List<string>>();
dictionary.Add("5.72", new List<string> { "a", "bbb", "cccc" });
dictionary.Add("fifty two", new List<string> { "a", "bbb", "cccc" });

foreach (KeyValuePair<string, List<string>> price in dictionary)
{
    double ylevel = Convert.ToDouble(price.Key);
}

Solution

To resolve this problem, you should use the following code:

var dictionary = new Dictionary<string, List<string>>();
dictionary.Add("5.72", new List<string> { "a", "bbb", "cccc" });
dictionary.Add("fifty two", new List<string> { "a", "bbb", "cccc" });

foreach (KeyValuePair<string, List<string>> price in dictionary)
{
    double ylevel;
    if(double.TryParse(price.Key, out ylevel))
    {
     //do something with ylevel
    }
    else
    {
     //Log price.Key and handle this condition
    }
}
Michael La Voie
Great.Thanks a lot !
Bernard Larouche
A: 

This is telling you that the string (that happens to be the key, although this is unrelated to the problem) cannot be parsed into a double. Check the value of the string you are attempting to convert.

GraemeF
A: 

double ylevel = Convert.ToDouble(price.Key.GetHashCode());

ElGringoGrande