I understand that this is an old question (before John Skeet?), But I myself have been considering this issue recently. Unfortunately, the current answers here (in my opinion) do not mention the most obvious advantage of the exit report.
The biggest benefit of the yield statement is that it allows you to iterate over very large lists with much more efficient use of memory, and then use a standard list.
For example, let's say you have a database query that returns 1 million rows. You can retrieve all rows using the DataReader and store them in a list, so for this you need to specify list_size * row_size bytes of memory.
Or you can use the yield statement to create an Iterator and only ever store one line in memory at a time. In fact, this gives you the ability to provide “streaming” usage over large data sets.
Also, in code that uses Iterator, you use a simple foreach loop and you can decide to exit the loop as needed. If you break early, you are not forced to restore the entire data set when you only need the first 5 rows (for example).
Regarding
Ideally some problem that cannot be solved some other way
The yield statement does not give you anything you could not do using your own iterator implementation, but it eliminates the need to write often complex code. There are very few problems (if any) that cannot solve more than one way.
Here are some more recent questions and answers that provide more detailed information:
Added value to a keyword?
Is revenue useful outside LINQ?
Ash Nov 07 '09 at 11:05 2009-11-07 11:05
source share