Let’s start with some source data to query:
int[] someData = { 1, 2 };
After running the following code, things work as I expect: a contains 2 elements which boil down to 1 and 2 pulled from someData.
List<IEnumerable<int>> a = new List<IEnumerable<int>>();
a.Add(someData.Where(n => n == 1));
a.Add(someData.Where(n => n == 2));
But this next code, which does exactly the same thing only in a loop, does not work as expected. When this code completes, b contains 2 elements but they are both identical – pointing to 2. On the 2nd loop, it modifies the first element of b.
List<IEnumerable<int>> b = new List<IEnumerable<int>>();
for (int i = 1; i <= 2; ++i)
{
b.Add(someData.Where(n => n == i));
}
Why is this happening and how can I make the loop version behave like the first version?
Jon Skeet has a nice answer here
You need to assign
ito atempvariable and use that in the Linq query