Reputation: 33
I have a list of POCO objects, why is it that the following code:
elements.Where(x => x.Param1 == "M").Select(x => x.Param2= "").ToList();
(TL;DR; sets param2 = "" on every element which param1 equals M)
updates the enumerable while this one:
elements.Where(x => x.Param1 == "M").Select(x => x.Param2= "");
does not update it?
Notice that i'm doing neither elements = elements.Where...
nor var results = elements.Where...
Upvotes: 1
Views: 63
Reputation: 223277
Your second code snippet without ToList
is just a query. You need to iterate to actually execute it. Calling ToList
executes the original query and since in your Select
you are modifying a property of an object, you see the effect (or a side effect) in your original list. It is related to parameter passing in C#. Since your lambda expression in Select
is an anonymous method which is receiving a parameter object of the list. Later when you modify one of it's property you see the effect.
Similarly if you try to set the object to null
you will not see the side effect.
.Select(x => x = null).ToList();
Upvotes: 2