C# 在LINQ中求和
从XML文档C# 在LINQ中求和,c#,linq,C#,Linq,从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
<?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>
....
我收到错误:“无法将type system.xml.linq.xmldattribute转换为int”我不确定您为什么在此处使用查询表达式,但我想您需要:
int sum = doc.Descendants("Product")
.Sum(x => (int) x.Attribute("ProductPrice"));
重要的一点是,这使用了,它允许您指定一个从源元素到整数值的函数。谢谢。我对Linq不熟悉。因此不太熟悉如何应用计算。谢谢您的建议。很抱歉,我们必须使用(双)x.Attribute(“ProductPrice”)而不是int。您确定要双精度而不是十进制吗?对于价格而言,使用float/double很少是一个好主意。你会遇到困难的。
int sum = doc.Descendants("Product")
.Sum(x => (int) x.Attribute("ProductPrice"));