c# - 以 double 转换字典键

标签 c# dictionary

我认为这并不复杂,但经过一些研究后我找不到一个简单问题的答案。

我正在遍历字典中的键,我想在某些计算中使用作为 double 字符串的键。

如果我这样做:

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

它似乎不起作用,我收到“输入字符串的格式不正确”错误。

从 key 中获得加倍的正确方法是什么..

谢谢

伯纳德

最佳答案

你做得对。

错误消息表明您的其中一个 key 实际上不是 double 值。

如果您在调试器中逐步执行此示例,您将看到它在第二项上失败:

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

关于c# - 以 double 转换字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1924547/

相关文章:

c# - 苔藓 : Running code when creating a site from a template?

c# - 在 WPF DataGrid 中禁用选择

c# - 什么是 C# 线程类型?

python - 将 xml 转换为 python 字典

c# - "The type ' 系统.Windows.Forms.TreeNodeCollection ' has no constructors defined"

c# - 从字符串中删除定义的部分

swift - 如何将 NSDictionary 转换为字典?

dictionary - 避免需要冗余检查以映射给定的字符串零值?

python - 如何遍历 Jinja 模板中的字典列表?

c++ - 模板 C++:如何访问 std::map 和 std::set 的迭代器值?