2009-12-17 33 views
4

我认为这并不复杂,但经过一番研究后,我找不到一个简单问题的答案。双字典键转换

我通过字典中的键迭代,我想在某些计算中使用字符串作为双精度的键。

如果我这样做:

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

它似乎没有工作,我得到一个“输入字符串的不正确的格式”的错误。

什么是正确的方式从密钥获得双..

感谢

伯纳德

+0

你确定所有的钥匙都是有效的双打吗? – 2009-12-17 21:01:38

+0

您可以发布(部分)您的字典的内容 – ChrisF 2009-12-17 21:03:04

+0

请注意,双重语法可能因国家/语言/机器/用户而异。 – ChrisW 2009-12-17 21:08:49

回答

5

你做正确。

错误消息表明您的其中一个键实际上不是双精度型。

如果你通过这个例子在调试步骤,你会看到它失败的第二个项目:

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 
    } 
} 
+0

太好了。 非常感谢! – 2009-12-17 21:10:29

0

这是告诉你,字符串(这恰好是关键,虽然这是无关的问题)不能被解析成双。检查您尝试转换的字符串的值。

0

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