English 中文(简体)
• 在没有使用准则的阵列中打上先线吗?
原标题:Obtain first string in an array which is not null using 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;
      }
}

因此,根据该法典,txt盒现在应当显示test”

我有这一法典。 罚款。 但是,我要知道,是否有可能利用LINQ获得同样的结果,或许会利用外围通道跳跃?

最佳回答

你可以这样做:

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 回归无效,如果没有任何要素可达到标准。

问题回答

仅举一个有趣的替代语种,以表明你并不总是需要用lam或匿名方法使用LINQ:

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

http://www.net.4.0。 IsNullOrEmpty

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签