Is there ever a reason to not use 'yield return' when returning an IEnumerable?

后端 未结 5 729
北海茫月
北海茫月 2020-12-09 16:16

Simple example - you have a method or a property that returns an IEnumerable and the caller is iterating over that in a foreach() loop. Should you always be using

5条回答
  •  [愿得一人]
    2020-12-09 16:40

    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 returning 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...
    

提交回复
热议问题