Get the first row in an array that is not null using LINQ?

I have a string array and I need to use the first string in a string array that is not null. Let's look at this piece of code -

string[] strDesc = new string[] {"", "", "test"}; foreach (var Desc in strDesc) { if (!string.IsNullOrEmpty(Desc)) { txtbox.Text = Desc; break; } } 

So, according to this snippet of code, txtbox should now display "test" .

For this, I have this code. This is working fine. But, I want to know if LINQ can be used to get the same result, and perhaps skipped with an extra foreach loop?

+4
source share
3 answers

You can do it as follows:

 var result = strDesc.First(s => !string.IsNullOrEmpty(s)); 

Or if you want to install it directly in the text box:

 txtbox.Text = strDesc.First(s => !string.IsNullOrEmpty(s)); 

Keep in mind that First will throw an exception if the string does not meet the criteria, so you might want to do:

 txtbox.Text = strDesc.FirstOrDefault(s => !string.IsNullOrEmpty(s)); 

FirstOrDefault returns null if no items define criteria.

+9
source

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(); 
+8
source

in .net 4.0 you can use IsNullOrWhiteSpace , but in earlier versions you need IsNullOrEmpty

 string desc = strDec.Where(s => !string.IsNullOrWhitespace(s)) .FirstOrDefault() ?? "None found"; txtBox.Text = desc; 
+1
source

All Articles