Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Why do you want to write an iterator class? The whole point of an iterator block is so you don't have to...</p> <p>i.e.</p> <pre><code>public IEnumerator&lt;T&gt; GetEnumerator() { int position = 0; // state while(whatever) { position++; yield return ...something...; } } </code></pre> <p>If you add more context (i,e, why the above can't work), we can probably help more.</p> <p>But if possible, avoid writing an iterator class. They are lots of work, and easy to get wrong.</p> <p>By the way, you don't really have to bother with <code>Reset</code> - it is largely deprecated, and shouldn't really ever be used (since it can't be relied to work for an arbitrary enumerator).</p> <p>If you want to consume an inner iterator, that is fine too:</p> <pre><code>int position = 0; foreach(var item in source) { position++; yield return position; } </code></pre> <p>or if you only have an enumerator:</p> <pre><code>while(iter.MoveNext()) { position++; yield return iter.Current; } </code></pre> <p>You might also consider adding the state (as a tuple) to the thing you yield:</p> <pre><code>class MyState&lt;T&gt; { public int Position {get;private set;} public T Current {get;private set;} public MyState(int position, T current) {...} // assign } ... yield return new MyState&lt;Foo&gt;(position, item); </code></pre> <p>Finally, you could use a LINQ-style extension/delegate approach, with an <code>Action&lt;int,T&gt;</code> to supply the position and value to the caller:</p> <pre><code> static void Main() { var values = new[] { "a", "b", "c" }; values.ForEach((pos, s) =&gt; Console.WriteLine("{0}: {1}", pos, s)); } static void ForEach&lt;T&gt;( this IEnumerable&lt;T&gt; source, Action&lt;int, T&gt; action) { if (source == null) throw new ArgumentNullException("source"); if (action == null) throw new ArgumentNullException("action"); int position = 0; foreach (T item in source) { action(position++, item); } } </code></pre> <p>Outputs:</p> <pre><code>0: a 1: b 2: c </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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