這裏我們可以使用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