简体   繁体   English

使用LINQ为集合中的所有对象的属性赋值的最佳方法

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

I have a Car object with a ResaleValue property, and I have a collection of these car objects stored in: 我有一个带有ResaleValue属性的Car对象,我将这些car对象的集合存储在:

 IEnumerable<Car>

I also have a ResaleCalculator() with a calculate method. 我还有一个带有计算方法的ResaleCalculator()。

Is there a way in linq to apply a calculation and set the ResaleValue property of every object in the collection without a loop? 在linq中有没有办法应用计算并在没有循环的情况下设置集合中每个对象的ResaleValue属性?

You don't really want to use LINQ for this. 你真的不想使用LINQ。 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. 其次,LINQ方法旨在过滤和/或投射序列,而不是使其变异。 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. 虽然你可以使用List<T>上的.ForEach 实例方法来不显式地编写循环,但是简单地编写循环来完成你需要它做的事情并不是很清楚。

我想这会做你想要的

cars.Select(c=>c.ResaleValue = c.Calculate());

You can't modify the IEnumerable<T> without projecting into a new IEnumerable with those values set to the ResaleValue property and copying over the existing properties. 您无法修改IEnumerable<T>而无需将这些值设置为ResaleValue属性并复制现有属性,从而无法投影到新的IEnumerable中。 Ideally you would do this when you first get your IEnumerable<Car> . 理想情况下,当你第一次获得IEnumerable<Car>时,你会这样做。

IEnumerable<Car> cars = // however you set cars originally
cars = cars.Select(c => new Car
            {
                Prop1 = c.Prop1,
                Prop2 = c.Prop2,
                ResaleValue = ResaleCalculator(params)
             });

Clearly this is not ideal. 显然这并不理想。 On the other hand, you could ToList() your collection and use the ForEach method or a regular foreach loop: 另一方面,您可以ToList()您的集合并使用ForEach方法或常规foreach循环:

var list = cars.ToList()
               .ForEach(c => c.ResaleValue = ResaleCalculator(c.SomeNeededParam));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM