2012-07-24 114 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