Iterator blocks perform a "live" evaluation each time they are iterated.
Sometimes, however, the behavior you want is for the results to be a "snapshot" at a point in time. In these cases you probably don't want to use yield return
, but instead return a List<>
or Set
, or some other persistent collection instead.
It's also unnecessary to use yield return
if you're dealing with query objects directly. This is often the case with LINQ queries - it's better to just return the IEnumerable<>
from the query rather than iterating and yield return
ing results yourself. For example:
var result = from obj in someCollection
where obj.Value < someValue
select new { obj.Name, obj.Value };
foreach( var item in result )
yield return item; // THIS IS UNNECESSARY....
// just return {result} instead...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…