I thought I know everything about IEnumerable
but I just met a case that I cannot explain. When we call .Where linq method on a IEnumerable
Like many LINQ operations, Select is lazy and use deferred execution so your lambda expression is never being executed, because you're calling Select
but never using the results. This is why, everything work fine after calling .ToList()
just after calling GenerateEnumerableTest()
method:
var tab = CTest.GenerateEnumerableTest().ToList();
var tab = CTest.GenerateEnumerableTest();
This tab
is a LINQ query that generates CTest
instances that are initialized from int
-values which come from an integer array which will never change. So whenever you ask for this query you will get the "same" instances(with the original Amount
).
If you want to "materialize" this query you could use ToList
and then change them.
Otherwise you are modifying CTest
instances that exist only in the first foreach
loop. The second loop enumerates other CTest
instances with the unmodified Amount
.
So the query contains the informations how to get the items, you could also call the method directly:
foreach (var item in CTest.GenerateEnumerableTest().Where(i => i.Amount > 6))
{
item.Amount = item.Amount * 2;
}
foreach (var t in CTest.GenerateEnumerableTest())
{
// now you don't expect them to be changed, do you?
}