6

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?

1
  • 1
    Resharper is very helpful in such situations as it can tell when the loop can be converted to Linq and can actually convert it too. Commented Nov 10, 2010 at 9:02

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

OrDefault, incase there are no null strings.
8

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

3 Comments

First() throws an exception if strDesc contains only nulls. So, FirstOrDefault() can be used instead.
@Pavanred - yes I am aware of that, but you didn't define what behaviour you wanted if nothing was found. And since the question seems to expect at least one, throwing an exception may be the correct thing to do.
Yes, Of Course, Thanks. I noticed this when I tried it out and thought it would be good to share.
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.