Take the code below, adapted from this question:
//Borrowed from another question because its a simpler example of what happened to me.
IEnumerable<char> query = "Not what you might expect";
foreach(char vowel in "aeiou")
{
query = query.Where(c => c != vowel);
}
foreach (char Output in query)
{
System.Out.WriteLine(Output);
}
This only removes the 'u' from the query char collection. The core issue has something to do with the fact that the 'c' variable in the Where clause isn't evaluated until the second foreach. My question is:
1) Why would the delegate generated by the first foreach not capture each value of c as it is built up? Is there some situation I'm unaware of where that is not the desired behavior?
2) If its not capturing the value of c, 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 c is clearly out of scope.
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.