I have an object model:
public class Quantity { public decimal Weight { get; set; } public decimal Volume { get; set; } // perhaps more decimals... public static Quantity operator +(Quantity quantity1, Quantity quantity2) { return new Quantity() { Weight = quantity1.Weight + quantity2.Weight, Volume = quantity1.Volume + quantity2.Volume }; } } public class OrderDetail { public Quantity Quantity { get; set; } } public class Order { public IEnumerable<OrderDetail> OrderDetails { get; set; } }
Now I want to introduce the readonly TotalQuantity property in the Order class, which should sum the amounts of all OrderDetails.
I am wondering if there is a better way to "LINQ":
public class Order {
This is not a good solution, as it is repeated twice through OrderDetails. And something like this is not supported (even if the + operator is present in the Quantity class):
Quantity totalQuantity = OrderDetails.Sum(o => o.Quantity);
Is there a better way to build the total amount in LINQ?
(For theoretical interest only, a simple foreach loop would also do its job well).
Thanks for the feedback!
Slauma
source share