pavanred
pavanred

Reputation: 13803

Obtain first string in an array which is not null using 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?

Upvotes: 6

Views: 10459

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062790

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();

Upvotes: 8

Preet Sangha
Preet Sangha

Reputation: 65496

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;

Upvotes: 1

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

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.

Upvotes: 11

Related Questions