When creating new objects in a LINQ statement, for example:
var list = new List<string>() { "a", "b", "c" };
var created = from i in list select new A();
With class A looking like this:
class A
{
public string Label;
}
And then modifying properties in A with a foreach loop:
foreach (var c in created) {
c.Label = "Set";
}
Why are the values not set when accessing the objects in the IEnumerable
afterwards. E.g. the following assertion fails:
Assert.AreEqual("Set", created.ElementAt(2).Label);
I wonder why this happens. I would expect the foreach-statement to execute the query, and trigger the creation of the objects. MSDN documentation states: "Execution of the query is deferred until the query variable is iterated over in a foreach or For Each loop".
I have reproduced this behavior with .NET 4.5 and Mono 3.2.0. Calling ToList
on the IEnumerable
before accessing the created object makes this problem go away.
A
s are created. – Janycreated
is a query not a collection. Everytime you access it you execute it again. So if you enumerate the query again after theforeach
you will get a fresh new set ofIEnumerable<A>
. That's the nature of deferred execution. If you would have queried an existing collection ofA
's you would change existing objects which would be persistent. – Mulciber