这里我们可以使用Foreach方法的List。请注意,原来的产品将被修改:
using System;
using System.Collections.Generic;
_kContext.Products.ToList().ForEach(product => {
if (product.DiscountRate >= 0.3) {
product.Price += 10;
}
});
如果你不希望你的原始对象进行修改,你可以使用LINQ选择的更多信息:使用替代版本属性构造使:
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)
});
我应该为我的Foreach代码添加一个库吗?由于v.s表示无法解析符号Foreach .. – cagin 2012-07-24 09:21:40
您应该通过调用ToList()将IEnumerable强制转换为IList。我已经修复了代码示例 –
2012-07-24 09:22:44
请问,如果有什么不能按预期工作 – 2012-07-24 09:26:17