使用LINQ获取一个非空的数组中的第一个字符串?

时间:2010-11-10 08:57:39

标签: c# linq

我有一个字符串数组,我需要在字符串数组中使用非空的第一个字符串。让我们考虑一下这段代码 -

string[] strDesc = new string[] {"", "", "test"};

foreach (var Desc in strDesc)
{
      if (!string.IsNullOrEmpty(Desc))
      {
           txtbox.Text = Desc;
           break;
      }
}

因此,根据此代码段,txtbox现在应显示"test"

要做到这一点,我有这个代码。这工作正常。但是,我想知道是否可以使用LINQ获得相同的结果,并且可能跳过使用额外的foreach循环?

3 个答案:

答案 0 :(得分:11)

你可以这样做:

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

或者如果您想直接在文本框中设置它:

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

请注意,如果没有字符串符合条件,First将抛出异常,因此您可能希望这样做:

txtbox.Text = strDesc.FirstOrDefault(s => !string.IsNullOrEmpty(s));
如果没有元素计算标准,

FirstOrDefault将返回null。

答案 1 :(得分:8)

只是一个有趣的替代语法,表明你并不总是需要使用lambdas或匿名方法来使用LINQ:

string s = strDesc.SkipWhile(string.IsNullOrEmpty).First();

答案 2 :(得分:1)

<。>在.net 4.0中,您可以使用IsNullOrWhiteSpace,但在早期版本中,您需要IsNullOrEmpty

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