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

clinq

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

Best Answer

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.