Sum of items in the collection

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

I know how to execute a new LINQ query for the database to find the total order amount, but since I already have the OrderDetails collection from the database, there is an easy way to return the LineTotal amount directly from the collection

I would like to add the total order amount as a property of my Order class. I suppose I could scroll through the collection and calculate the sum using for each Order.OrderDetail, but I guess there is a better way.

+65
linq sum
Sep 15 '08 at 4:53
source share
1 answer

You can use LINQ for objects and use LINQ to calculate totals:

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

You can also use lambda expressions for this, which is a bit cleaner.

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

Then you can connect this to your Order class if you want:

 Public Partial Class Order { ... Public Decimal LineTotal { get { return orderdetailscollection.Sum(od => od.LineTotal); } } } 
+148
Sep 15 '08 at 5:02
source share



All Articles