2012-07-24 117 views
1

我有產品對象。產品對象具有DiscountRate和Price屬性。我想要改變價格,具體取決於折扣率功能。我想爲我的所有產品對象執行此操作。這裏是我的代碼:在實體對象中循環並設置對象的屬性

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

你有什麼建議嗎?

回答

2

這裏我們可以使用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) 
}); 
+0

我應該爲我的Foreach代碼添加一個庫嗎?由於v.s表示無法解析符號Foreach .. – cagin 2012-07-24 09:21:40

+0

您應該通過調用ToList()將IEnumerable強制轉換爲IList 。我已經修復了代碼示例 – 2012-07-24 09:22:44

+0

請問,如果有什麼不能按預期工作 – 2012-07-24 09:26:17