简体   繁体   English

LINQ FirstOrDefault 还是 DefaultIfEmpty?

[英]LINQ FirstOrDefault or DefaultIfEmpty?

I'm getting confused about how to use FirstOrDefault or DefaultIfEmpty.我对如何使用 FirstOrDefault 或 DefaultIfEmpty 感到困惑。

The snippet below may be empty, but if it's not, I definitely want the first one.下面的片段可能是空的,但如果不是,我肯定想要第一个。

var vThr = _context.PostThrs.FirstOrDefault(m => 
            m.ThrZero == zero 
            && m.ThrText.Substring(0,8) == "SERVICE-");

If it is empty, I would like the result to be "Empty".如果它是空的,我希望结果是“空的”。 How would I do that?我该怎么做? I've taken some stabs at it, but I'm not sure that it's helpful to share.我已经对此进行了一些尝试,但我不确定分享是否有帮助。

EDIT: After posting, I realized that the question doesn't really work as you cannot insert a single string into the result/编辑:发布后,我意识到这个问题并没有真正起作用,因为你不能在结果中插入单个字符串/

Summarize between:总结:

.FirstOrDefault() .DefaultIfEmpty()
Query with the result of the first item that fulfills.使用第一个满足的项目的结果进行查询。 Query with the result of IEnumerable .使用IEnumerable的结果进行查询。 Use to initialize a default item if the sequence is empty.如果序列为空,则用于初始化默认项。
- If there is item(s) fulfilled, return the first T item. - 如果有项目已履行,则返回第一个T项目。 If there is item(s) fulfilled, return at least one or more T items as IEnumerable<T> .如果有项目已履行,则将至少一个或多个T项目返回为IEnumerable<T>
- If not, returns default . - 如果不是,则返回default - If not, the defaultValue parameter is used to initialize into IEnumerable<T> . - 如果不是,则使用defaultValue参数初始化为IEnumerable<T> Returns an IEnumerable<T> with a single item ( Count = 1).返回带有单个项目 ( Count = 1) 的IEnumerable<T>

So, based on your requirement, you are looking for .FirstOrDefault() to check the returned result is null and perform the following implementation.因此,根据您的要求,您正在寻找.FirstOrDefault()来检查返回的结果是否为null并执行以下实现。

Didn't cover the part that you want to assign an "Empty" string to the variable when null and you found out that it is not feasible to do as the variable is T which will conflict with the type.没有涵盖您想要在null时为变量分配“空”字符串的部分,并且您发现这样做是不可行的,因为变量是T会与类型冲突。


References参考

.FirstOrDefault()

.DefaultIfEmpty()

使用 FirstOrDefault() 它会找到条件元素的第一个匹配项,但如果不是,则只返回 null

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

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