Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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.


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

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

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

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

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;
}