Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy doesn't deferred execution cache iterative values?
    text
    copied!<p>Take the code below, adapted from <a href="https://stackoverflow.com/questions/652742/linq-caveats/652749#652749">this question</a>:</p> <pre><code>//Borrowed from another question because its a simpler example of what happened to me. IEnumerable&lt;char&gt; query = "Not what you might expect"; foreach(char vowel in "aeiou") { query = query.Where(c =&gt; c != vowel); } foreach (char Output in query) { System.Out.WriteLine(Output); } </code></pre> <p>This only removes the 'u' from the query char collection. The core issue has something to do with the fact that the <code>c</code> variable in the <code>Where</code> clause isn't evaluated until the second foreach. My question is:</p> <p>1) Why would the delegate generated by the first foreach not capture each value of <code>c</code> as it is built up? Is there some situation I'm unaware of where that is not the desired behavior?</p> <p>2) If its not capturing the value of <code>c</code>, how is that value even still in scope in the second foreach when the query is actually run? It would seem to me that if its not storing the values of the variables being passed in, then trying to resolve the statement for the second foreach would fail because the the variable <code>c</code> is clearly out of scope. </p> <p>I don't understand how it is that 'use the last value we saw on this variable back when it was in scope' was a good design decision for this circumstance, and was hoping someone could shed some light on the subject.</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