I'm having problems with this simple code and I don't understand why c# behaves this way.
The problem seems to be that c# uses the Linq expression reference instead of the value when using Lists inside Lists.
On the loop for numbers I select the numbers based on the list, they all exist so all numbers should be added to the list {1,2,3}.
The behavior is ok when you see the output from the console it show {1,2,3} inside the numbers loop.
The problem is on the loop of the list, in here it seems that Linq only adds the last number to the list so it outputs {3,3,3}.
I know I don't need a list of ints inside the list but it's just to prove a point it's very weird, is this a known "bug"?
EDIT: It seems that this is how it is supposed to work in c# prior to 5.0. In C# 5.0 (VS2012+ compiler) this behavior has been modified to what I would expect
static void Main()
{
var list = new List<IEnumerable<int>>();
var numbers = new[] {1, 2, 3};
var numbers2 = new[] {1, 2, 3};
foreach (var number in numbers)
{
var result = from s in numbers2
where s == number
select s;
Console.WriteLine(result.First()); // outputs {1,2,3}
list.Add(result);
}
foreach (var num in list)
{
Console.WriteLine(num.First()); // outputs {3,3,3}
}
}
Output
1 2 3 3 3 3