I encountered a (for me) strange behaviour. Here is the code:
var objects = from i in items
//some calculations
select something;
// other calculations
objects.ToList().ForEach(x => {
//some calculations
x.Property = "some text"
});
return objects;
First I generate a IEnumerable
, it is a query to the db, I skipped the details.
Then I have to do other calculations and at the end I iterate over my objects to set a further parameter. Running this code, once the IEnumerable
objects is returned, their Property
is not set.
Otherwise if I move the ToList()
in the Linq expression as followed, the Property
is set:
var objects = (from i in items
//some calculations
select something).ToList();
// other calculations
objects.ForEach(x => {
//some calculations
x.Property = "some text"
});
return objects;
As far I know, the objects are not copied, but referenced...right? What does behind the apparently codes happen? What is the difference?