score:8

Accepted answer

first off, this is not a good idea. see below for arguments against it.

it doesn't work. the property value is not changed. why?

it doesn't work because select() doesn't actually iterate through the collection until you enumerate it's results, and it requires an expression that evaluates to a value.

if you make your expression return a value, and add something that will fully evaluate the query, such as tolist(), to the end, then it will "work", ie:

myobjectcollection.select(myobject => { myobject.myproperty = newvalue; return myobject;}).tolist();

that being said, tolist() has some disadvantages - mainly, it's doing a lot of extra work (to create a list<t>) that's not needed, which adds a large cost. avoiding it would require enumerating the collection:

foreach(var obj in myobjectcollection.select(myobject => { myobject.myproperty = newvalue; return myobject; })) 
{ }

again, i wouldn't recommend this. at this point, the select option is far uglier, more typing, etc. it's also a violation of the expectations involved with linq - linq is about querying, which suggests there shouldn't be side effects when using linq, and the entire purpose here is to create side effects.

but then, at this point, you're better off (with less typing) doing it the "clear" way:

foreach (var obj in myobjectcollection)
{
     obj.myproperty = newvalue;
}

this is shorter, very clear in its intent, and very clean.

note that you can add a foreach<t> extension method which performs an action on each object, but i would still recommend avoiding that. eric lippert wrote a great blog post about the subject that is worth a read: "foreach" vs "foreach".

score:0

as sircodesalot mentioned, you can't use linq to do something like that. remember that linq is a querying language, which means all you can do is query it. doing changes must be done in other logic.

what you could do, if you don't want to do it the first way and if your collection is a list already (but not an ienumerable) you can use the foreach extension method in linq to do what you're asking.

one other point i should mention is that the select method does a projection of some specific information to return to an ienumerable. so, if you wanted to grab only a specific property from a collection you would use that. that's all it does.


Related Query

More Query from same tag