paparazzo
paparazzo

Reputation: 45096

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.

Upvotes: 3

Views: 964

Answers (2)

Matt D
Matt D

Reputation: 397

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

Upvotes: 1

DavidG
DavidG

Reputation: 118937

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.

Upvotes: 6

Related Questions