简体   繁体   中英

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( ?? ) :

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

If all strings are in a collection you can use 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:

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.

Make a IEnumerable of strings (list or array....), then you can use .All()

var myStrings = new List<string>{string1,string2,string3....};
if(myStrings.All(s => s == null))
{
   //Do something
}

In case you want to check null or empty , here is another way without arrays:

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;

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;

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)){...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM