【问题标题】:How to get value from dictionary by key and compare that value with zero c#?如何按键从字典中获取值并将该值与零 c# 进行比较?
【发布时间】:2020-06-02 18:45:44
【问题描述】:

我有字典,如果值(非键)

public Dictionary<string, double> Components = new Dictionary<string, double>();

if (/*Components key amount < 0*/)
 {
   throw new Exception("Value can't be smaller then 0!");
 }

【问题讨论】:

  • 您只是在需要检索错误值时才尝试检查它们?
  • 您不是在问“如何通过键从字典中获取值并将该值与零进行比较,例如Components["Amount"]&lt; 0”?请edit 发布并澄清您期望发生的情况,显示输入数据和所需的输出。随意同时删除Error 和switch 的无关代码。

标签: c# .net validation


【解决方案1】:

只需获取给定键的值并检查该值是什么:

double value;
if (Components.TryGetValue(key, out value) && value < 0)
{
    throw new Exception("Value can't be smaller then 0!");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 2018-09-26
    相关资源
    最近更新 更多