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

相关文章:

c# - Put Attempted on document using non current Etag 错误

c# - .net 控制台应用程序在连续打印出大量字符时停止响应

sql-server - LINQ:DataContext Life 和 System.Data.SqlClient.SqlException:超时已过期

c# - 多次读取 IEnumerable

c# - 在 MVVM 中定义从模型到 View 的属性更改的理想方法是什么?

c# - Unity C# : Camera Control Using Automatic Positioning & Mouse Look

c# - EF 核心 : Update object graph duplicates child entities

c# - EF Core 2.1 在分组后进行子查询和聚合时在本地进行评估

c# - 将空值转换为空 IEnumerable<T> 的 Linq 方法?

c# - 如何从 Sitefinity 10 中的动态模块集合中检索图像数据?