tags:

views:

1114

answers:

5

Using LINQ, if I wanted to perform some query and return the object from the query, but change only some of the properties in that object, how would I do this without creating a new object and manually set every property? Is this possible?

Example:

var list = from something in someList
           select x // but change one property
+9  A: 

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.

JaredPar
Thanks, your solution works nicely. How would you write it using query syntax?
Rob Volk
@Rob, Not easily. The syntax to get that working is ... unreadable at best. var query = from it in list select ((Func<Foo>)(() => { it.x = 42; return it; }))();
JaredPar
Btw, this won't work in LINQ to SQL, for obvious reasons.
Mehrdad Afshari
A: 

It is not possible with the standard query operators - it is Language Integrated Query, not Language Integrated Update. But you could hide your update in 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;
       }
    }
}

Now you can use it as follows.

cars.Where(car => car.Color == Color.Blue).ChangeColorTo(Color.Red);
Daniel Brückner
Cool, I like the chaining.
David
A: 

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;
}
Joshua Belden
A: 
var item = (from something in someList
       select x).firstordefault();

Would get the item, and then you could do item.prop1=5; to change the specific property.

Or are you wanting to get a list of items from the db and have it change the property prop1 on each item in that returned list to a specified value? if so you could do this (I'm doing it in VB because I know it better):

dim list = from something in someList select x
for each item in list
    item.prop1=5
next

(list will contain all the items returned with your changes)

Solmead
+3  A: 

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

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

Jon Spokes