我认为这并不复杂,但经过一些研究后,我找不到一个简单问题的答案.
我正在迭代字典中的键,我想在一些计算中使用键作为双字符串.
如果我这样做:
foreach (KeyValuePair<string, List<string> price in dictionary)
double ylevel = Convert.ToDouble(price.Key);
Run Code Online (Sandbox Code Playgroud)
它似乎不起作用,我得到一个"输入字符串格式不正确"错误.
什么是从钥匙中获得双倍的正确方法..
谢谢
伯纳德
你正确地做到了.
错误消息表明您的一个键实际上不是双精度键.
如果您在调试器中单步执行此示例,您将在第二个项目上看到它失败:
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);
}
Run Code Online (Sandbox Code Playgroud)
解
要解决此问题,您应该使用以下代码:
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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
842 次 |
| 最近记录: |