c# - c# 通用 if 语句
问题描述
我有 4 个列表。其中一些充满了数据,而另一些则为空。我想做一个 if 语句,它只考虑包含元素的列表,如果列表为空,我不想在 if 条件下看到它。
List<int> list1 = new List<int> {1,2,3 };
List<string> list2 = new List<string>();
List<string> list3 = new List<string> { "cc", "cc", "cc" };
List<string> list4 = new List<string> { "dd", "dd", "dd" };
if (list1.Contains(1) && list2.Contains("bb") && list3.Contains("cc") && list4.Contains("dd"))
{
MessageBox.Show("condition okey");
}
正如您在代码示例中看到的,list2 是空的,我不想将它包含在 if 语句中。我从数据库中填写这些列表。我不知道,哪一个会是空的。
我怎样才能写一个通用的 if 语句。谢谢你。
解决方案
也许您可以使用?: 运算符来确定列表是否包含元素。如果不是,直接返回true。
if ((list1.Count != 0 ? list1.Contains(1) : true )
&& (list2.Count != 0 ? list2.Contains("bb") : true)
&& (list3.Count != 0 ? list3.Contains("cc") : true)
&& (list4.Count != 0 ? list4.Contains("dd") : true))
{
MessageBox.Show("condition okey");
}
推荐阅读
- intellij-idea - 无法使用 gradle 将 YAML 添加到 Intellij
- dynamics-crm - 访问/导出 CRM 365 审计日志数据
- javascript - 如何缓存文本区域?
- javascript - 使用同一组件中的方法在 Vue 组件中查找特定数据时遇到问题
- ignite - Apache Ignite 瘦客户端事件
- python - 为什么 Sentry 推荐的 Django 日志记录配置使来自 django.db.backends 的日志记录静音?
- javascript - js如何在屏幕上移动动画
- php - Mysql将数据插入double类型
- python - 我想知道如何在 Python 中计算两种 numpy 数组类型的相似度(数值精度)
- jquery - 通过 bgcolor 属性选择元素