Reputation: 4303
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".
Upvotes: 2
Views: 1630
Reputation: 1504182
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.
Upvotes: 9