Difference in LINQ Query Results in .NET 3.5 and 4.5

I have executed the following code with C # 3.5 and 4.0. The results are completely different.

static void Main() { int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; List<IEnumerable<int>> results = new List<IEnumerable<int>>(); foreach (var num in numbers) { results.Add(numbers.Where(item => item > num)); } foreach (var r in results) { Console.WriteLine("{0}", r.Count()); } } 

With Microsoft (R) Visual C # 2008 compiler version 3.5.30729.5420 output 0 0 0 0 0 0 0 0 0 0 .

But with Microsoft (R) Visual C # compiler version 4.0.30319.17929 output 9 8 7 6 5 4 3 2 1 0 .

I have a faint idea that this is due to deferred execution or lazy assessment, but do not clearly understand how he is responsible for the various results here.

Correction: Sorry that these were versions of .NET 3.5 and 4.5, and compiler versions were added. Please explain.

+7
c # linq
source share
2 answers

Since C # 5, the loop variable in foreach compiled so that it exists inside the loop area, and not outside it.

This means that when you close the loop variable, you get different results.

Here, what Eric Lippert had to say about the original problem.

+7
source share

You got access to the variable inside the closure, so the results will differ in different versions of the compiler.

In C # 5.0, a variable is redefined at each iteration of the loop, whereas in previous versions of C # it was defined only once.

For more information see Eric Lippert great blog post.

Moreover, the opening paragraph:

UPDATE: We are making changes. In C # 5, a foreach loop variable will be logically inside the loop, and therefore closures will be closed by a new copy of the variable each time. The for loop will not be changed. We will return you to our original article.

+6
source share

All Articles