你做正确。
错误消息表明您的其中一个键实际上不是双精度型。
如果你通过这个例子在调试步骤,你会看到它失败的第二个项目:
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);
}
解决方案
要解决这个问题,你应该使用下面的代码:
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
}
}
你确定所有的钥匙都是有效的双打吗? – 2009-12-17 21:01:38
您可以发布(部分)您的字典的内容 – ChrisF 2009-12-17 21:03:04
请注意,双重语法可能因国家/语言/机器/用户而异。 – ChrisW 2009-12-17 21:08:49