[英]Checking several string for null in an if statement
是否有更好(更好)的方式来编写这个if语句?
if(string1 == null && string2 == null && string3 == null && string4 == null && string5 == null && string6 == null){...}
Perhaps using the null-coalescing operator( ??
) : 也许使用null-coalescing运算符(
??
) :
if((string1 ?? string2 ?? string3 ?? string4 ?? string5 ?? string6) == null){ ;}
If all strings are in a collection you can use Linq: 如果所有字符串都在集合中,您可以使用Linq:
bool allNull = strings.All(s => s == null);
You could put all the strings in a list and use 您可以将所有字符串放在列表中并使用
if(listOfStrings.All(s=>s==null))
At the very least you can put it on multiple lines 至少你可以把它放在多行上
if(string1 == null
&& string2 == null
&& string3 == null
&& string4 == null
&& string5 == null
&& string6 == null)
{...}
If you made a function like this: 如果你做了这样的功能:
public static bool AllNull(params string[] strings)
{
return strings.All(s => s == null);
}
Then you could call it like this: 然后你可以这样称呼它:
if (AllNull(string1, string2, string3, string4, string5, string6))
{
// ...
}
Actually, you could change AllNull() to work with any reference type, like this: 实际上,您可以更改AllNull()以使用任何引用类型,如下所示:
public static bool AllNull(params object[] objects)
{
return objects.All(s => s == null);
}
string[] strs = new string[] { string1, string2, string3 };
if(strs.All(str => string.IsNullOrEmpty(str))
{
//Do Stuff
}
Or use strs.All(str => str == null)
if you don't want to check for empty strings. 或者如果您不想检查空字符串,请使用
strs.All(str => str == null)
。
In case you want to check null or empty , here is another way without arrays: 如果你想检查null 或为空 ,这是没有数组的另一种方法:
if (string.Concat(string1, string2, string3, string4, string5).Length == 0)
{
//all null or empty!
}
Well, I don't know if it is nicer or better , or not, you can use IEnumerable.Any method like this; 好吧,我不知道它是否更好或更好 ,你可以使用IEnumerable.Any这样的方法;
Determines whether a sequence contains any elements.
确定序列是否包含任何元素。
List<string> list = new List<string>{"string1","string2","string3", "string4", "string5"};
if(list.Any(n => n == null))
{
}
And you can use Enumerable.All() method like; 并且您可以使用Enumerable.All()方法;
Determines whether all elements of a sequence satisfy a condition.
确定序列的所有元素是否满足条件。
if (Enumerable.All(new string[] { string1, string2, string3, string4, string5 }, s => s == null) )
{
Console.WriteLine("Null");
}
这应该做同样的事情:
if (string.IsNullOrEmpty(string1 + string2 + string3 + string4 + string5 + string6)){...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.