Question

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.

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?

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.

Was it helpful?

Solution

You can do LINQ to Objects and the use LINQ to calculate the totals:

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

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);
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top