LINQ: Select an object and change some properties without creating a new object

I want to change some properties of a LINQ query result object without creating a new object and manually setting every property. Is this possible?

Example:

var list = from something in someList
           select x // but change one property

Solution 1:

I'm not sure what the query syntax is. But here is the expanded LINQ expression example.

var query = someList.Select(x => { x.SomeProp = "foo"; return x; })

What this does is use an anonymous method vs and expression. This allows you to use several statements in one lambda. So you can combine the two operations of setting the property and returning the object into this somewhat succinct method.

Solution 2:

If you just want to update the property on all elements then

someList.All(x => { x.SomeProp = "foo"; return true; })

Solution 3:

I prefer this one. It can be combined with other linq commands.

from item in list
let xyz = item.PropertyToChange = calcValue()
select item

Solution 4:

There shouldn't be any LINQ magic keeping you from doing this. Don't use projection though that'll return an anonymous type.

User u = UserCollection.FirstOrDefault(u => u.Id == 1);
u.FirstName = "Bob"

That will modify the real object, as well as:

foreach (User u in UserCollection.Where(u => u.Id > 10)
{
    u.Property = SomeValue;
}