集合中项目的总和 [英] Sum of items in a collection

查看:69
本文介绍了集合中项目的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用LINQ to SQL,我有一个Order类,其中包含OrderDetails的集合.订单明细具有一个名为LineTotal的属性,该属性获得Qnty x ItemPrice.

Using LINQ to SQL, I have an Order class with a collection of OrderDetails. The Order Details has a property called LineTotal which gets Qnty x ItemPrice.

我知道如何对数据库执行新的LINQ查询以查找订单总额,但是由于我已经从数据库中获得了OrderDetails的集合,因此有一种简单的方法可以直接从集合中返回LineTotal的总和?

I know how to do a new LINQ query of the database to find the order total, but as I already have the collection of OrderDetails from the DB, is there a simple method to return the sum of the LineTotal directly from the collection?

我想将订单总计添加为我的Order类的属性.我想我可以遍历集合并为每个Order.OrderDetail用a计算总和,但是我猜有更好的方法.

I'd like to add the order total as a property of my Order class. I imagine I could loop through the collection and calculate the sum with a for each Order.OrderDetail, but I'm guessing there is a better way.

推荐答案

您可以对对象执行LINQ,并使用LINQ计算总数:

You can do LINQ to Objects and the use LINQ to calculate the totals:

decimal sumLineTotal = (from od in orderdetailscollection
select od.LineTotal).Sum();

您还可以使用lambda-expressions来执行此操作,这有点干净".

You can also use lambda-expressions to do this, which is a bit "cleaner".

decimal sumLineTotal = orderdetailscollection.Sum(od => od.LineTotal);

然后,您可以根据需要将其连接到Order类:

You can then hook this up to your Order-class like this if you want:

Public Partial Class Order {
  ...
  Public Decimal LineTotal {
    get {
      return orderdetailscollection.Sum(od => od.LineTotal);
    }
  }
}

这篇关于集合中项目的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆