简体   繁体   中英

Finding Sum in LINQ

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" .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM