我为每个循环都有以下内容来获取所有子对象的总和.使用LINQ有更好的方法吗?
Purchase p1 = db.Purchases.FirstOrDefault(p => p.PurchaseId == 1);
int total = 0;
foreach (SellingItem item in p1.SellingItems)
{
total = total + Convert.ToInt32(item.Price);
}
Run Code Online (Sandbox Code Playgroud)

参考:
Jon*_*eet 11
听起来你只是想要:
// Any reason for FirstOrDefault rather than SingleOrDefault?
var purchase = db.Purchases.FirstOrDefault(p => p.PurchaseId == 1);
if (purchase != null)
{
var total = purchase.SellingItems
.Sum(x => Convert.ToInt32(x.Price));
...
}
// TODO: Work out what to do if there aren't any such purchases
Run Code Online (Sandbox Code Playgroud)
为什么你需要转换价格呢?什么类型Price,为什么它不是正确的类型?(那真的想成为int而不是decimal吗?)
| 归档时间: |
|
| 查看次数: |
3986 次 |
| 最近记录: |