首页 > 解决方案 > 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 语句。谢谢你。

标签: c#if-statement

解决方案


也许您可以使用?: 运算符来确定列表是否包含元素。如果不是,直接返回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");
}

推荐阅读