简体   繁体   English

Linq的FirstOrDefault

[英]FirstOrDefault in Linq

I am trying to move this foreach loop to linq: 我试图将这个foreach循环移动到linq:

compData = componentData[0];
foreach (var componentTraceData in componentData)
{
     if (!string.IsNullOrEmpty(componentTraceData.CompName))
     {
          compData = componentTraceData;
          break;
     }
}

And this is what I tried: 这就是我试过的:

var tt = (from n in componentData 
          where !string.IsNullOrEmpty(n.CompName) 
          select n).FirstOrDefault();

How I can make it to take componentData[0] in case linq not found any results ? 如果linq没有找到任何结果,我怎么能让它采取componentData[0]

Take the line you currently have and add ?? componentData[0] 拿你目前的线路并添加?? componentData[0] ?? componentData[0] at the end. ?? componentData[0]结尾。

?? is the null coalescing operator. 是空合并运算符。 It's just shorthand for, "if what's to my left is null, return what's on my right. If it's not null, return that." 这只是简写,“如果我左边的内容为null,则返回我右边的内容。如果它不为null,则返回。”

You can use Enumerable.DefaultIfEmpty and specify a custom default value: 您可以使用Enumerable.DefaultIfEmpty并指定自定义默认值:

var result = componentData.Where(n => !string.IsNullOrEmpty(n.CompName))
                          .DefaultIfEmpty(componentData.ElementAtOrDefault(0))
                          .First();

Note that you can now use First safely since the sequence cannot be empty anymore. 请注意,您现在可以安全地使用First ,因为序列不能再为空。 ElementAtOrDefault will return default(T) (null for reference types) if the source sequence is empty. 如果源序列为空, ElementAtOrDefault将返回default(T) (引用类型为null)。 This will prevent an exception when you use the indexer of an IList<T> directly. 当您直接使用IList<T>的索引器时,这将防止异常。

var tt = componentData.FirstOrDefault(n=!string.IsNullOrEmpty(n.CompName)) ?? componentData[0];

虽然您想要检查componentData为null,并且count / length也是大于零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM