In the following example, changes applied in the foreach are not preserved when I return the collection:
var people = SomeLinqToSqlSource();
foreach (var person in people)
{
person.Name = "Jimmy";
}
return people.AsQueryable();
This contradicts my understanding that within a foreach(..), you operate by-reference on the current item.
Could anybody please let me know where I’m going wrong?
Thanks.
The problem is that
peopleis anIQueryableand is re-queried when you return it and the consumer enumerates the results – your updated properties are gone now, since eachpersoninstance is reconstructed by executing the query.If you want to preserve changes you have to materialize your data first, i.e. using
ToList()and then return the list as anIEnumerable(orIList)