Sum of items in a collection

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

Leave a Comment