[英]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.