How do I return the first string variable that isn't null or empty
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
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) …
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) );