[ACCEPTED]-Obtain first string in an array which is not null using LINQ?-linq
Accepted answer
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.
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();
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;
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.