简体   繁体   English

LINQ中是否推迟了FirstOrDefault?

[英]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. 代码将不止一次引用analysisSport

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. 就像您可以ToList()来使LINQ立即和一次进行评估。

FirstOrDefault has the same effect as ToList on an enumerable in terms of it only enumerating a single time. FirstOrDefaultToList对枚举具有相同的作用,因为它仅枚举一次。

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. 由于FirstOrDefault返回一个具体的对象(或者当然为null),因此没有可枚举的内容。

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. 另外一个潜在的陷阱是IEnumerableanalysisSport任何子属性,根据其基础类型,它们可能会被多次枚举。

.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. .Where将查找与约束匹配的所有元素,然后使用.FirstOrDefault ,它将返回从.Where获得的可枚举列表中的第一个元素,除非它为空,否则它将返回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();

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

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