LINQ:获得所有子项目总和的有效方法

时间:2012-07-27 12:29:43

标签: c# .net linq

我为每个循环都有以下内容来获取所有子对象的总和。使用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);
}

enter image description here

参考:

  1. How to get the sum of the volume of highest and lowest priced items in linq

  2. Using the ALL operator in linq to filter child items of EntitySet

2 个答案:

答案 0 :(得分: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

为什么你需要转换价格呢?什么类型是Price,为什么它不是正确的类型? (那真的想成为int而不是decimal吗?)

答案 1 :(得分:1)

尝试使用Linq Sum方法:

Purchase p1 = db.Purchases.FirstOrDefault(p => p.PurchaseId == 1);

int total = p1.SellingItems.Sum(item => Convert.ToInt32(item.Price));

效率不高,因为它不会更快。但它更简洁。