Sum of items in a collection

LinqSum

Linq Problem Overview


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.

Linq Solutions


Solution 1 - Linq

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);
    }
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdrianView Question on Stackoverflow
Solution 1 - LinqEspoView Answer on Stackoverflow