I'm reading Albahari O'Reilly's book, C # in a nutshell, and I'm in the Linq Query chapter. It describes the effect of delayed execution and variable capture when executing Linq queries. He gives the following common error example:
IEnumerable<char> query = "Not what you might expect";
string vowels = "aeiou";
for (int i = 0; i < vowels.Length; i++)
{
query = query.Where(c => c != vowels[i]);
}
foreach (var c in query)
{
Console.WriteLine(c);
}
Console.Read();
An IndexOutOfRangeExceptionis called after the request, but that makes no sense to me. I would expect that the lambda expression in the Where statement c => c!= vowles[i]would simply be evaluated in c => c != vowels[4]for the entire sequence due to the effect of delayed execution and variable capture. I went ahead and debugged to find out what the value iwas when the exception was raised, and found out that it had a value of 5? So, I went ahead and changed the condition condition in the for loop to i < vowels.Length-1;, and, indeed, no exception was thrown. Is the for loop iiterating on the most recent iteration to 5 or is linq doing somenthing else?
source
share