Friday, January 21, 2011

Sum of items in a collection

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.

  • 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);
        }
      }
    }
    
    aku : Arghh! You outran me this time. Anyway +1 vote.
    Omer van Kloeten : note that the order class should be partial, since it's already been generated by the LINQ to SQL generator.
    Espo : aku: Finally, thanks for the vote :) Omer: Thank you, i will update the code
    From Espo

0 comments:

Post a Comment