linq - Double-use of C# iterator works unexpectedly -


this first go @ coding in c# - have background in c/python/javascript/haskell.

why program below work? expect work in haskell, lists immutable, struggling how can use same iterator nums twice, without error.

using system; using system.collections.generic; using system.linq; using system.text;  namespace helloworld {     class program     {         static void main(string[] args)         {             var nums = new list<int?>() { 0, 0, 2, 3, 3, 3, 4 };             var lastnums = new list<int?>() { null } .concat(nums);             var changesandnulls = lastnums.zip(nums,                 (last, curr) => (last == null || last != curr) ? curr : null             );             var changes = changeornull in changesandnulls changeornull != null select changeornull;              foreach (var change in changes) {               console.writeline("change: " + change);             }         }     } } 

in code nums not ienumerator<t> (iterator), it's ienumarable<t> , ienumarable <t> has getenumerator() method can invoked many times required:

ienumerable<int?> nums = new list<int?>() { 0, 0, 2, 3, 3, 3, 4 };  // linq gets enumerator concat  using (var iterator1 = nums.getenumerator()) {    while (iterator1.movenext()) {      ...    } }  ...  // linq gets (fresh!) enumerator zip  using (var iterator2 = nums.getenumerator()) {    while (iterator2.movenext()) {     ...    } }  

so ienumerable<t> factory producing ienumerator<t> instances (and ienumerator<t> can't re-used)


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -