Coder Perfect

LINQ: Select an object and modify its properties without having to create a new one.


I’d like to alter several properties of a LINQ query result object without having to create a new object and set each property manually. Is that even possible?


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

Asked by Rob Volk

Solution #1

I’m not sure how to write a query. However, here is a more detailed LINQ expression example.

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

This replaces an expression with an anonymous method. This allows you to combine many statements into a single lambda. As a result, you can use this method to combine the two procedures of setting the property and returning the object.

Answered by JaredPar

Solution #2

If all you want to do is update the property on all elements, this is the way to go.

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

Answered by Jon Spokes

Solution #3

This is the one I favor. It’s possible to use it in conjunction with other Linq instructions.

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

Answered by Jan Zahradník

Solution #4

You shouldn’t be able to do this because of any LINQ wizardry. If you utilize projection, you’ll get an anonymous type.

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

This will change the physical object as well as:

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

Answered by Joshua Belden

Solution #5

Language Integrated Query, not Language Integrated Update, is not achievable with normal query operators. However, you might be able to disguise your change via extension methods.

public static class UpdateExtension
    public static IEnumerable<Car> ChangeColorTo(
       this IEnumerable<Car> cars, Color color)
       foreach (Car car in cars)
          car.Color = color;
          yield return car;

You can now utilize it in the following manner.

cars.Where(car => car.Color == Color.Blue).ChangeColorTo(Color.Red);

Answered by Daniel Brückner

Post is based on