Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain first string in an array which is not null using LINQ?

Tags:

c#

linq

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?

like image 858
pavanred Avatar asked Nov 10 '10 08:11

pavanred


2 Answers

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.

like image 135
Klaus Byskov Pedersen Avatar answered Oct 13 '22 00:10

Klaus Byskov Pedersen


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();
like image 36
Marc Gravell Avatar answered Oct 13 '22 00:10

Marc Gravell