1

我有产品对象。Product 对象具有 DiscountRate 和 Price 属性。我想根据折扣率功能更改价格。我想对我所有的 Product 对象执行此操作。这是我的代码:

    public IEnumerable<Product> GetAll()
    {
        //I want to set change price in here. 
        return _kContext.Products.ToList();
    }

你有什么建议吗?

4

1 回答 1

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)
 });
于 2012-07-24T09:15:49.990 回答