我有产品对象。产品对象具有DiscountRate和Price属性。我想改变价格,具体取决于折扣率功能。我想为我的所有Product对象执行此操作。这是我的代码:
public IEnumerable<Product> GetAll()
{
//I want to set change price in here.
return _kContext.Products.ToList();
}
你有什么建议吗?
答案 0 :(得分:2)
这里我们可以使用List的Foreach方法。请注意,原始产品将被修改:
using System;
using System.Collections.Generic;
_kContext.Products.ToList().ForEach(product => {
if (product.DiscountRate >= 0.3) {
product.Price += 10;
}
});
如果您不想修改原始对象,可以使用Linq Select:
using System.Linq;
return _kContext.Products.Select(product => {
var newProduct = new Product();
newProduct.Price = product.Price;
newProduct.DiscountRate = product.DiscountRate;
if (newProduct.DiscountRate >= 0.3) {
newProduct.Price += 10;
}
return newProduct;
});
编辑:使用属性构造函数的替代版本,以使更多可读。
using System.Linq;
return _kContext.Products.Select(product => new Product {
DiscountRate = product.DiscountRate,
Price = product.Price + ((product.DiscountRate >= 0.3) ? 10 : 0)
});