Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

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

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 'yield return' in your IEnumerable method? Is there ever a reason not to? While I understand that it may not always be necessary to, or even "better" (maybe it's a very small collection for example), is there ever a reason to actively avoid doing this?

The bit of code that got me thinking about this was a function I wrote very similar to the accepted answer in this thread - How do I loop through a date range?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...