c# - 如何按键从字典中获取值并将该值与零 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!");
}
解决方案
只需获取给定键的值并检查该值是什么:
double value;
if (Components.TryGetValue(key, out value) && value < 0)
{
throw new Exception("Value can't be smaller then 0!");
}
推荐阅读
- asp.net - 无法在工作项目目录之外发布 ASP.Net Core SPA 应用程序
- node.js - 关于 sequelize 迁移的快速问题
- python-3.x - 如何在 Python 中有效且完全地使用标志从另一个线程中杀死 main() 线程?
- laravel - 从另一个与 Eloquent 和 Laravel 8 的关系中获取关系
- haskell - 如何使用“isPrefixOf”将 Haskell(或)运算符添加到变量中
- python - 如何避免导入模块导入?你能在运行时动态生成 __all__ 吗?
- visual-studio-code - Visual Studio 代码调试器未启动
- php - 如果 12 个月内不是周六或周日,则显示最后一个工作日
- botframework - 如何使用 Bot Framework Composer 在 MS Teams 中捕获用户电子邮件
- python - 获取文件中的重复行