你做正確。
錯誤消息表明您的其中一個鍵實際上不是雙精度型。
如果你通過這個例子在調試步驟,你會看到它失敗的第二個項目:
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