简体   繁体   中英

LINQ FirstOrDefault or DefaultIfEmpty?

I'm getting confused about how to use FirstOrDefault or 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 . Use to initialize a default item if the sequence is empty.
- If there is item(s) fulfilled, return the first T item. If there is item(s) fulfilled, return at least one or more T items as IEnumerable<T> .
- If not, returns default . - If not, the defaultValue parameter is used to initialize into IEnumerable<T> . Returns an IEnumerable<T> with a single item ( Count = 1).

So, based on your requirement, you are looking for .FirstOrDefault() to check the returned result is null and perform the following implementation.

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.


References

.FirstOrDefault()

.DefaultIfEmpty()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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