在if语句中检查多个字符串是否为空

38

如果语句有更好(更优雅)的写法,该怎么办?

if(string1 == null && string2 == null && string3 == null && string4 == null && string5 == null && string6 == null){...}

1
如果(String.IsNullOrWhiteSpace(string1)&& ...) -> 这样你不仅检查 null 字符串,还要检查空字符串和一些仅包含空格的字符串。 - Offler
3
你真的需要那么多单独的字符串变量吗?你不能创建一个字符串数组或列表并使用它来替代吗?这很可能也会简化许多其他操作。 - John Willemse
1
根据您提供的信息,不太可能(如果需要,可以将其分成几行),但@JohnWillemse的观点是正确的。如果您需要这么多字符串变量,也许需要考虑使用一些不同的数据结构来封装此逻辑。 - Matt Burland
就我个人而言,我会完全按照那样的方式编写它。尽管我认为除非它们在某种集合中,否则我永远不会有那么多要测试是否为空的字符串。 - Matthew Watson
谢谢大家的回答。使用列表是一个好主意,但我也喜欢Tim使用null-coalescing运算符的解决方案,所以我接受了他的答案。 - Dušan
8个回答

63

也许可以使用空值合并运算符(??):

if((string1 ?? string2 ?? string3 ?? string4 ?? string5 ?? string6) == null){ ;}

如果所有字符串都在一个集合中,你可以使用 Linq:

bool allNull = strings.All(s => s == null);

15
你可以将所有的字符串放在一个列表中,并使用。
if(listOfStrings.All(s=>s==null))

至少可以把它分成多行

if(string1 == null 
   && string2 == null 
   && string3 == null 
   && string4 == null 
   && string5 == null 
   && string6 == null)
{...}

我使用了 || 而不是 && 来解决中间的空值问题。 - Shaiju T
@stom 你所说的“在空值之间”是什么意思?如果你使用||而不是&&,你只会得到至少一个值为空,而不是所有值都为空。 - juharr

14

如果你创建了下面这样的一个函数:

public static bool AllNull(params string[] strings)
{
    return strings.All(s => s == null);
}

那么你可以这样调用它:

if (AllNull(string1, string2, string3, string4, string5, string6))
{
    // ...
}

实际上,您可以将AllNull()更改为适用于任何引用类型,如下所示:

public static bool AllNull(params object[] objects)
{
    return objects.All(s => s == null);
}

非常干净的解决方案!虽然与@Tim Schmelter的解决方案类似,但通过将其分离为函数并提供完整的示例,使其变得更加容易。 - PM.

6
string[] strs = new string[] { string1, string2, string3 };
if(strs.All(str => string.IsNullOrEmpty(str))
{
  //Do Stuff
}

如果您不想检查空字符串,请使用strs.All(str => str == null)


3
创建一个字符串的IEnumerable(列表或数组...),然后可以使用.All()函数,具体用法请参考.All()文档。
var myStrings = new List<string>{string1,string2,string3....};
if(myStrings.All(s => s == null))
{
   //Do something
}

2
或者在一行中... if (Enumerable.All(new string[] {str1, str2, str3, str4}, s => s == null)) - Jim Mischel
1
@JimMischel:这只是为了缩短评估而创建了一个额外的集合。顺便说一句,它甚至并没有真正缩短它。 - Tim Schmelter
@TimSchmelter:是的,它确实会创建一个额外的集合,就像你点赞的那个答案一样。 - Jim Mischel

2

嗯,我不知道是否更好或更美好,但是你可以像这样使用IEnumerable.Any方法:

确定序列是否包含任何元素。

List<string> list = new List<string>{"string1","string2","string3", "string4", "string5"};
if(list.Any(n => n == null))
{

}

您可以使用Enumerable.All()方法,例如:

确定序列的所有元素是否满足条件。

if (Enumerable.All(new string[] { string1, string2, string3, string4, string5 }, s => s == null) )
{
       Console.WriteLine("Null");
}

2
如果您想检查null或空值,这里有另一种不需要使用数组的方法:
if (string.Concat(string1, string2, string3, string4, string5).Length == 0)
{
    //all null or empty!
}

2
不检查是否全部为空,与Dennisch的答案相同。 - Tim Schmelter

1
这应该是相同的:

if (string.IsNullOrEmpty(string1 + string2 + string3 + string4 + string5 + string6)){...}

4
如果它们是空的,而不仅仅是 null,这将返回 True。 - Igoy
只需使用string.IsNullOrWhiteSpace来解决上述问题,非常简单。喜欢这种方法。 - kuskmen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接