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
8 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
-
3You don't need the Where, use msdn.microsoft.com/en-us/library/bb549039.aspx Mar 29, 2010 at 15:52
-
.FirstOrDefault(x=> !string.IsNullOrEmpty(x))
with an optional?? string.Empty
if you don't want nulls.– user1228Mar 29, 2010 at 15:57 -
What if first, second, third, .. were methods and I would want them to execute only until the first of them returned a not empty result. Then the other solution was better.– DavidMay 30, 2019 at 15:14
-
they were only string variables which may have string values or they might be null Nov 18, 2019 at 4:40
Define an extension method:
static string Or(this string value, string alternative) {
return string.IsNullOrEmpty(value) ? alternative : value;
}
Now you can say the following:
string result = str1.Or(str2).Or(str3).Or(str4) …
-
1Eh. S'kay, but not lazy-evaluated.– user1228Mar 29, 2010 at 16:02
-
If the first value is not null or empty, this will still check all the rest of the values, except for the last one. Four function calls where one would suffice. Mar 29, 2010 at 16:12
-
1@Robert Davis: Will is actually right, he just used odd wording; this version does not use short-circuit evaluation, whereas the
FirstOrDefault
method will in fact stop after the first element is found. If you're only comparing 5 elements, though, I wouldn't worry about it. Mar 29, 2010 at 16:23 -
1BTW, I use an extension method like this (uses NullOrWhiteSpace, lol 4.0) for display purposes, not for returning the first non-empty string in a collection. I use it like:
string.Format("Displaying item {0}", item.Name.Or("(no name given)"));
– user1228Mar 29, 2010 at 16:40 -
1@Jeffrey, @Will: that’s true and I almost considered not posting it. But truth be told, it doesn’t matter and I argue that this code is the most concise, most readable alternative. Would I use it myself? Not sure – but primarily because I oppose to generating lots of spurious, non-general extension methods, and not because it might be slow. Also consider that it might actually be more efficient than creating a list/array and iterating over it (using an iterator, which, once again, hast to be created). So, I remain unconvinced that performance is a reason against using this method. Mar 29, 2010 at 17:51
private static string FirstNonEmptyString(params string[] values)
{
return values.FirstOrDefault(x => !string.IsNullOrEmpty(x));
}
Called like this:
Console.WriteLine(FirstNonEmptyString(one, two, three, four, five) );
-
1I'd suggest a tweak to the name to FirstOrDefaultNonEmptyString (as if there are no non empty strings you'll get a null right?) Aug 18, 2019 at 11:35
If you have a fixed number of variables I would suggest to use the null coalescing operator to check for nulls. This is by far the easiest option.
var result = s1 ?? s2 ?? s3 ?? s4 ?? s5 ?? "";
There is in my opinion no need to do a separate function for that anymore given there is a language construct for it already.
Edit: Empty strings are considered non-null and thus if one of them is empty it will return it.
so if you want to use this together:
public static string EmtpyToNull(string value)
{
return string.IsNullOrEmpty(value) ? null : value;
}
var result = EmptyToNull(s1)
?? EmptyToNull(s2)
?? EmptyToNull(s3)
?? EmptyToNull(s4)
?? EmptyToNull(s5)
?? "";
-
1This needs more upvotes! There is a language construct for doing precisely this task, and it doesn't just work with strings.– MorvaelApr 28, 2021 at 14:27
-
2You might take a note that ?? operator works only against null values, not an empty strings, as asked by the op. But it is still useful to mention an existence of such operator. Jun 29, 2021 at 16:57
-
If your strings are in an IEnumerable
you can use First
or FirstOrDefault
:
strings.First(s => !string.IsNullOrEmpty(s))
-
1) this answer was already given 2)
First
throws an IOE if all strings are null or empty– user1228Mar 29, 2010 at 16:42 -
@Will, 1) I think I was the first to suggest First/FirstOrDefault as an obvious alternative to Where. 2) The questioner doesn't specify the behavior he wants in the case that all strings are null/empty. That's why I suggested both. Mar 29, 2010 at 16:55
-
hmmmm, was going on recollection about FOD. My bad. I don't believe he said anything in his question about throwing if all strings are null. You also didn't state that teensy little fact.
First
throwing is something people often don't realize and it ends up biting them in the ass. Thought it might be important for people reading to see that.– user1228Mar 29, 2010 at 19:46
var found = new[]{first, second, third, fourth, fifth}.FirstOrDefault(x =>!String.IsNullOrEmpty(x));
If you're using .NET 3.5 this is very easy with Linq.
string[] strings = new[] {"", "a", "b", ""};
string firstNotNullOrEmpty =
strings.Where(s => !String.IsNullOrEmpty(s)).FirstOrDefault();
-
1
First
has an override which makes theWhere
pointless. Also, if all strings are null you'd throw an InvalidOperationException here. Which would suck ass.– user1228Mar 29, 2010 at 16:02 -
1I find including the Where() makes it more readable. Why would it throw
InvalidOperationException
?– jrummellMar 29, 2010 at 16:12 -
open up LINQPad and try this:
(new string[] { (string)null }).First(x=>!string.IsNullOrEmpty(x))
You'll see it throws an IOE, as First() is designed to do if there are no matching results. FirstOrDefault() never throws if no matching results are found; it just returnsdefault(T)
.– user1228Mar 29, 2010 at 16:36 -
Right! You must have missed my update where I changed
First()
toFirstOrDefault()
=).– jrummellMar 29, 2010 at 16:48 -
I changed the spacing so that it appears on two lines and is more readable.– jrummellMar 29, 2010 at 16:50
Yes.
string selected = null;
foreach(string currStr in strArray)
if(String.IsNullOrEmpty(currStr)==false)
{
selected = currStr;
break;
}
No expression trees, no LINQ abuse, no obscure language features. Same runtime performance and a first year CS student can figure out what you're doing.
-
I feel bad for first year CS students who are kept safe from language features that make coding a joy.– user1228Mar 29, 2010 at 16:41
-
@Will: LINQ abuse is a serious issue affecting our community, lets all be part of the solution not the problem.– kervinMar 29, 2010 at 16:51
-
BTW I love LINQ, I just converted a XPath based library to LINQ to XML last week, and EF is my ORM of choice.– kervinMar 29, 2010 at 16:53
-
1How are the other codes “LINQ abuse”? How do you define that? And finally, how are six lines, one explicit loop, and a comparison to
false
(ugh!) any better than a concise, self-explanatory query that fits on one line? Mar 29, 2010 at 17:53