For each declaration of the where clause in the loop, there is a separate Func <int, bool> which is passed to it. Since the value I am passed to the lambda function associated with each instance of Func <int, bool> (Func <int, bool> is essentially a delegate), I am a captured variable that is shared by each instance of Func <int, bool>.
In other words, I have to be βleft aliveβ, even outside the scope of the loop, so that its value is evaluated whenever any instance of Func <int, bool> is called. This is usually not a problem, except that the call will not be made until it is needed (i.e., it is necessary to list the results of the request to which the delegate instance is passed. Example: this is a foreach: only loop, then the delegate will be called, to determine the results of a query for iteration purposes).
This means that LINQ queries declared in the loop will not actually be executed until some time after the for loop completes, which means that I will be set to 2. As a result, you are actually doing something like this:
b.Add(someData.Where(n => n == 2)); b.Add(someData.Where(n => n == 2));
To avoid this, for each iteration in the loop you need to declare a separate instance of the integer type and make it equivalent to i. Pass this to the lambda function declared in the iteration, and each Func <int, bool> instance will have a separate captured variable, the value of which will not be changed after each subsequent iteration. For instance:
for (int i = 1; i <= 2; ++i) { int j = i; b.Add(someData.Where(n => n == j)); }
source share