Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to assign a value to a property of all objects in a collection using LINQ

Tags:

c#

linq

I have a Car object with a ResaleValue property, and I have a collection of these car objects stored in:

 IEnumerable<Car>

I also have a ResaleCalculator() with a calculate method.

Is there a way in linq to apply a calculation and set the ResaleValue property of every object in the collection without a loop?

like image 901
leora Avatar asked Dec 03 '22 10:12

leora


2 Answers

You don't really want to use LINQ for this. Firstly, you're not avoiding a loop, you are merely abstracting it away. Secondly, LINQ methods are intended to filter and/or project a sequence, not mutate it. While you could use the .ForEach instance method on List<T> to not explicitly write a loop, it is hardly clearer than simply coding the loop to do what you need it to do.

like image 91
Anthony Pegram Avatar answered Jan 07 '23 11:01

Anthony Pegram


I think this will do what you want

cars.Select(c=>c.ResaleValue = c.Calculate());
like image 40
Iain Avatar answered Jan 07 '23 12:01

Iain