codingjoe
codingjoe

Reputation: 810

Lambda expression to manipulate a single field in a collection

I have a collection of objects where an object has some fields. I need to format one of the fields in the collection and still maintain the integrity of the collection.

Say for example I have a list of cars var myCars = new List<Car>();, and in that list of cars I want to change all color field from black to white by calling a ChangeColor(string color) method. Can I do that in one single line or do I need to make a new List and assign the fields one by one in a loop and call the change color method within that loop?

I want to see if there is an 'one-liner'

Thanks in advance.

Upvotes: 0

Views: 1560

Answers (4)

Dustin Kingen
Dustin Kingen

Reputation: 21265

Either use a foreach loop or the List(T).ForEach method.

myCars.ForEach(c => c.ChangeColor(newColor));

Upvotes: 3

evanmcdonnal
evanmcdonnal

Reputation: 48114

There is not. LINQ always returns new collections, it doesn't modify the one you're operating on. This is a problem because you need to change the color and also return a Car to do it in LINQ and it just doesn't work that way. Instead you just have to do foreach which can be done in one line here;

 foreach(var car in myCars) car.ChangeColor(newColor);

Actually, what I said at first is not true. You can do it, it's just ugly, much uglier than the non LINQ solution and also produces an entirely new collection. But you can do;

   var newColoredCars = myCars.Select(x => { x.ChangeColor(newColor); return x; } );

However that's horribly unreadable and modifies your existing collection and returns a new collection which is about the worst possible thing you could do here; modify your original collection then make a copy of it so you don't keep the original and use twice as much memory!

Upvotes: 1

Servy
Servy

Reputation: 203838

You should use a foreach loop to do something for each value in a collection:

foreach(var car in myCars) car.ChangeColor(newColor);

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460238

Don't use Linq to modify collections, instead use simple loops:

foreach(Car car in myCars)
    car.Color = color;

Upvotes: 1

Related Questions