Home > other >  LINQ FirstOrDefault or DefaultIfEmpty?
LINQ FirstOrDefault or DefaultIfEmpty?

Time:07-07

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/

CodePudding user response:

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()

CodePudding user response:

Use FirstOrDefault() it will find first matched by condition element but if not will return just null

  • Related