首页 > 解决方案 > 如何按键从字典中获取值并将该值与零 c# 进行比较?

问题描述

我有字典,如果值(不是键)<0,我想抛出异常。但我不知道如何检查这个条件。请帮帮我

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

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

标签: c#.netvalidation

解决方案


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

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

推荐阅读