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 'u' from the char request collection. The main problem is that the variable c in the Where clause is not evaluated until the second foreach. My question is:
1) Why does the delegate generated by the first foreach not capture every value of c as it is created? Is there any situation that I don’t know about where this is not the desired behavior?
2) If it does not fix the value of c , how is this value still stored in the region in the second foreach, when the request is actually executed? It seems to me that if you do not store the values of the transferred variables, then the attempt to resolve the operator for the second foreach will fail, because the variable c clearly beyond the scope.
I don’t understand how to “use the last value that we saw in this variable when it was in scope” was a good design decision for this circumstance, and I hoped that someone could shed some light on this topic.
source share