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

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

问题描述

使用 LINQ to SQL,我有一个包含 OrderDetails 集合的 Order 类.Order Details 有一个名为 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.OrderDetail 计算总和,但我猜有更好的方法.

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 to Objects 并使用 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 表达式来做到这一点,这有点干净".

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

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

如果需要,您可以像这样将其连接到您的订单类:

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天全站免登陆