Lets take a look at some of the ways to do that.
id: 0d712dcf48ef4642295cdfbe64464124 - page: 2
59 60 // Here's a variable to track execution of code in an iterator 61 int lastYielded = -1; 62 63 // Here's an iterator for us to play with 64 IEnumerable<int> GetOneToTen() { 65 for (var num = 1; num <= 10; num++) { 66 lastYielded = num; 67 yield return num; 68 } 69 } 70 71 void Main() { 72 var numbers = GetOneToTen(); 73 lastYielded.Dump(); // Output: -1 74 75 // This gives us an 'instance' of the iteration 76 var enumerator = numbers.GetEnumerator(); 77 78 // This executes the iterator until the first yield return is reached 79 enumerator.MoveNext(); 80 81 // This gives us the current (most recently yielded) value of the iterator 82 enumerator.Current.Dump(); // Output: 1 83 lastYielded.Dump(); // Output: 1 84 85 // This will iterate from 1 to 4, then stop 86 foreach (var num in numbers) { 87 if (num >= 4) { 88 break; 89 } 90 } 91 92 lastYielded.Dump(); // Output: 4 93 94 // This will not execute any code in the iterator. 95 // LINQ methods are lazily evaluated as well 96 var numb
id: 915b475fb2c33002d30139666b2d7a04 - page: 2
Select(num => num * 2); 97 lastYielded.Dump(); // Output: 4 98 99 // This will force the entire iterator to run, yielding all values
id: 79fd78dde3b68a822818ce46d8b908d8 - page: 2
100 var arr = numbers.ToArray(); 101 lastYielded.Dump(); // Output: 10 102 } 103 Its important to point out that many iterators are not as simple as the ones weve been using here. An iterator could query a database, for exampleincluding the unfortunate possibility that it might alter data, or that iterating through it twice might yield completely different results! Some tools (like ReSharper) will warn you against multiple enumeration for this reason. An iterator is, from one perspective, nothing more than a synchronous method that may not execute its code right away (or at all). And to muddy the waters just a little, not all iterators are synchronous; theres also an IAsyncEnumerable interface (you can loop through it with await foreach). 104 105 Most of the time none of this is a problem. Almost all the time you can treat an
id: 575a6822f89f466be372ec2d835444f5 - page: 2