Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>But what if you were building a collection yourself?</p> <p>In general, iterators can be used to <strong>lazily generate a sequence of objects</strong>. For example <code>Enumerable.Range</code> method does not have any kind of collection internally. It just generates the next number <strong>on demand</strong>. There are many uses to this lazy sequence generation using a state machine. Most of them are covered under <strong>functional programming concepts</strong>.</p> <p>In my opinion, if you are looking at iterators just as a way to enumerate through a collection (it's just one of the simplest use cases), you're going the wrong way. As I said, iterators are means for returning sequences. The sequence might even be <strong>infinite</strong>. There would be no way to return a list with infinite length and use the first 100 items. It <strong>has</strong> to be lazy sometimes. <strong>Returning a collection is considerably different from returning a collection generator</strong> (which is what an iterator is). It's comparing apples to oranges.</p> <p>Hypothetical example:</p> <pre><code>static IEnumerable&lt;int&gt; GetPrimeNumbers() { for (int num = 2; ; ++num) if (IsPrime(num)) yield return num; } static void Main() { foreach (var i in GetPrimeNumbers()) if (i &lt; 10000) Console.WriteLine(i); else break; } </code></pre> <p>This example prints prime numbers less than 10000. You can easily change it to print numbers less than a million without touching the prime number generation algorithm at all. In this example, you can't return a list of all prime numbers because the sequence is infinite and the consumer doesn't even know how many items it wants from the start.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload