I have a string array and I need to use the first string in the string array which is not null. Lets consider this code snippet -
string[] strDesc = new string[] {"", "", "test"};
foreach (var Desc in strDesc)
{
if (!string.IsNullOrEmpty(Desc))
{
txtbox.Text = Desc;
break;
}
}
So, according to this code snippet, txtbox should now display "test"
.
To do this I have this code. This is working fine. But, I want to know if it is possible to use LINQ to obtain the same result and perhaps skip using an extra foreach loop?
You can do it like this:
var result = strDesc.First(s => !string.IsNullOrEmpty(s));
Or if you want to set it directly in the textbox:
txtbox.Text = strDesc.First(s => !string.IsNullOrEmpty(s));
Mind you that First
will throw an exception if no string matches the criteria, so you might want to do:
txtbox.Text = strDesc.FirstOrDefault(s => !string.IsNullOrEmpty(s));
FirstOrDefault
returns null if no element mathces the criteria.
Just an interesting alternative syntax, to show that you don't always need lambdas or anonymous methods to use LINQ:
string s = strDesc.SkipWhile(string.IsNullOrEmpty).First();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With