如何使用 LINQ 获取 IEnumerable 中两个属性的乘积之和?

How do you get the sum of the product of two properties in an IEnumerable using LINQ?

我有一个 IEnumerable<dynamic> 来自使用 Dapper 的 SQL 查询,我想将 IEnumerable 中动态对象的两个属性的乘积加在一起。

我试过:

decimal total = orderDetails.Aggregate((workingTotal, detail) => 
    workingTotal + (detail.quantity * detail.unitPrice));

但是 returns 一个 object 无法转换为小数。

由于您使用的是动力学,编译器不知道 detail.quantity 等是什么。所以你需要明确地将它转换为 decimal.

decimal total = (decimal)orderDetails.Aggregate((workingTotal, detail) => 
     workingTotal + (detail.quantity * detail.unitPrice));

编译器不知道detail.quantitydetail.unitPrice的类型,所以你需要转换它们。 另外,你需要another Aggregate overload,一个种子值:

decimal total = orderDetails.Aggregate((decimal)0, (workingTotal, detail) =>
            workingTotal + ((decimal)detail.quantity * (decimal)detail.unitPrice));

当然,您可以使用 Sum 而不是 Aggregate - 更容易。

我会使用 Sum 而不是 Aggregate:

decimal total = orderDetails.Sum(x => (decimal) (x.quantity * x.unitPrice));

具体取决于您的具体情况,我可以想象这可能在没有任何演员表的情况下工作,或者需要更多演员表......用 dynamic.

并不总是那么容易分辨