Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return the first string variable that isn't null or empty

Tags:

c#

.net-3.5

If I have 5 String variables and between 0 and 5 of them are null or empty is there an easy/short way of returning the first one that is not null or empty? I am using .NET 3.5

like image 485
Ben Hoffman Avatar asked Mar 29 '10 15:03

Ben Hoffman


People also ask

How do you check if a string is not null and not empty in Java?

Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string.

How do you check if a string is null or not?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.

Is null and empty string the same?

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.

Does string isEmpty check for null?

isEmpty(<string>) Checks if the <string> value is an empty string containing no characters or whitespace. Returns true if the string is null or empty.


1 Answers

var myString = new string[]{first, second, third, fouth, fifth}       .FirstOrDefault(s => !string.IsNullOrEmpty(s)) ?? "";  //if myString == "", then none of the strings contained a value   

edit: removed Where(), placed predicate in FirstOrDefault(), thanks Yuriy

like image 83
dan Avatar answered Sep 26 '22 19:09

dan