<p>If I have an IEnumerator variable is it possible to have a lambda function that takes it, advances it with MoveNext() and returns the Current value every single time its called?</p>

[{'answer_id': 72963, 'author': 'Abe Heidebrecht', 'author_id': 9268, 'author_profile': 'https://Stackoverflow.com/users/9268', 'pm_score': 1, 'selected': False, 'text': '<p>A Lambda expression can contain complex statements, so you can do the following:</p>\n\n<pre><code>Func&lt;IEnumerator, object&gt; f = ie =&gt; { ie.MoveNext(); return ie.Current; };\n</code></pre>\n'}, {'answer_id': 73007, 'author': 'Jonathan Rupp', 'author_id': 12502, 'author_profile': 'https://Stackoverflow.com/users/12502', 'pm_score': 3, 'selected': True, 'text': '<pre><code>e =&gt; e.MoveNext() ? e.Current : null\n</code></pre>\n\n<p>This will advance the enumerator and return the current value, and return null when the enumeration is complete.</p>\n'}, {'answer_id': 73041, 'author': 'fryguybob', 'author_id': 4592, 'author_profile': 'https://Stackoverflow.com/users/4592', 'pm_score': 0, 'selected': False, 'text': '<p>Is this what you are looking for?</p>\n\n<pre><code>List&lt;string&gt; strings = new List&lt;string&gt;()\n{\n    "Hello", "I", "am", "a", "list", "of", "strings."\n};\nIEnumerator&lt;string&gt; e = strings.GetEnumerator();\nFunc&lt;string&gt; f = () =&gt; e.MoveNext() ? e.Current : null;\nfor (; ; )\n{\n    string str = f();\n    if (str == null)\n        break;\n\n    Console.Write(str + " ");\n}\n</code></pre>\n\n<p>The point of an <code>IEnumerator</code> is that you already get syntactic sugar to deal with it:</p>\n\n<pre><code>foreach (string str in strings)\n    Console.Write(str + " ");\n</code></pre>\n\n<p>Even handling the enumerator directly looks cleaner in this case:</p>\n\n<pre><code>while (e.MoveNext())\n    Console.Write(e.Current + " ");\n</code></pre>\n'}, {'answer_id': 73058, 'author': 'Nathan Baulch', 'author_id': 8799, 'author_profile': 'https://Stackoverflow.com/users/8799', 'pm_score': 0, 'selected': False, 'text': '<p>Extending on Abe\'s solution, you can also use closures to hold a reference to the enumerator:</p>\n\n<pre><code>var iter = ((IEnumerable&lt;char&gt;)"hello").GetEnumerator();\n\n//with closure\n{\n    Func&lt;object&gt; f =\n        () =&gt;\n            {\n                iter.MoveNext();\n                return iter.Current;\n            };\n    Console.WriteLine(f());\n    Console.WriteLine(f());\n}\n\n//without closure\n{\n    Func&lt;IEnumerator, object&gt; f =\n        ie =&gt;\n            {\n                ie.MoveNext();\n                return ie.Current;\n            };\n    Console.WriteLine(f(iter));\n    Console.WriteLine(f(iter));\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/72913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5056/']