[ACCEPTED]-Obtain first string in an array which is not null using LINQ?-linq

Accepted answer
Score: 11

You can do it like this:

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

Or if you want to 5 set it directly in the textbox:

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

Mind you 4 that First will throw an exception if no string 3 matches the criteria, so you might want 2 to do:

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

FirstOrDefault returns null if no element mathces 1 the criteria.

Score: 8

Just an interesting alternative syntax, to 2 show that you don't always need lambdas 1 or anonymous methods to use LINQ:

string s = strDesc.SkipWhile(string.IsNullOrEmpty).First();
Score: 1

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

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

More Related questions