I have an IEnumerable<dynamic>
from an SQL query using Dapper, and I would like to add together the product of two properties of the dynamic objects in the IEnumerable
.
I tried:
decimal total = orderDetails.Aggregate((workingTotal, detail) =>
workingTotal + (detail.quantity * detail.unitPrice));
but that returns an object
that cannot be converted to a decimal.
I would use Sum
instead of Aggregate
:
decimal total = orderDetails.Sum(x => (decimal) (x.quantity * x.unitPrice));
Depending on exactly what your situation is, I can imagine this potentially working without any casts, or needing more casts... it's not always easy to tell with dynamic
.
See more on this question at Stackoverflow