简体   繁体   中英

Is FirstOrDefault deferred in LINQ?

Consider this statement:

StandardLookUpList analysisSport = lookupItem.Where(w => w.Code == Constants.Sport).FirstOrDefault();

Code is going to refer to analysisSport more than once.

Will that statement be evaluated more than once?

If it will be evaluated more than once is the a way to get it to evaluate once?

Like you can to ToList() to get LINQ to evaluate immediately and once.

FirstOrDefault has the same effect as ToList on an enumerable in terms of it only enumerating a single time.

The only time you need to be concerned about multiple enumeration is, funnily enough when you have an enumerable! Since FirstOrDefault returns a concrete object (or a null of course), there's nothing there to enumerate.

One additional potential pitfall would be any child properties of analysisSport that are IEnumerable , they may be enumerated multiple times depending on their underlying type.

.Where is going to find all elements matching your constraints, and then you're using .FirstOrDefault which will return the first element in the enumerable list you got from .Where , unless it is empty, then it will return null.

And no, after that line of code is executed, it will not be evaluated any more. If you want it to be evaluated again, you will have to set it again:

StandardLookUpList analysisSport = lookupItem.Where(w => w.Code == Constants.Sport).FirstOrDefault();

// now changing the variable to show cars instead of sports
analysisSport = lookupItem.Where(w => w.Code == Constants.Cars).FirstOrDefault();

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