来自 XML 文档
<?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>
....
如何使用“Sum”求出 ProductPrice 的总和?
当我使用
XDocument doc = XDocument.Load("Product.xml");
var sum =
from tot in (int)doc.Descendants("Product").
Attributes("ProductPrice").Sum()
select tot;
我收到错误:“无法将类型 system.xml.linq.xmlattribute 转换为 int”。
最佳答案
我不确定你为什么要在这里使用查询表达式,但我想你想要:
int sum = doc.Descendants("Product")
.Sum(x => (int) x.Attribute("ProductPrice"));
重要的一点是这使用了 overload of Sum
它允许您指定一个函数以从源元素转到整数值。
关于c# - 在 LINQ 中求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1713566/