tags:

views:

144

answers:

1

From the XML Document

<?xml version="1.0" encoding="utf-8" ?> 
 <Data>
   <Products>
      <Product ProductId="1001" ProductName="ProductA" ProductPrice="123.45" /> 
      <Product ProductId="1002" ProductName="ProductB" ProductPrice="100.45" /> 
  </Products>
  ....

How to use "Sum" to find the sum of ProductPrice?

When i use

XDocument doc = XDocument.Load("Product.xml");

var sum =
          from tot in (int)doc.Descendants("Product").
                       Attributes("ProductPrice").Sum()
                       select tot;

I receive Error : "can not convert type system.xml.linq.xmlattribute to int".

+8  A: 

I'm not sure why you're using a query expression here, but I think you want:

int sum = doc.Descendants("Product")
             .Sum(x => (int) x.Attribute("ProductPrice"));

The important point is that this uses the overload of Sum which lets you specify a function to go from the source element to the integer value.

Jon Skeet
Thank you.I am new to Linq.So not quite familiar how to apply calculations.Thanks for your suggestion.
Sorry we have to use (double) x.Attribute("ProductPrice") instead of int.
Are you sure you want double rather than decimal? Using float/double is rarely a good idea for prices. You'll run into rounding difficulties.
Jon Skeet