【问题标题】:How can I use XElement to retrieve the Sum of an Attribute?如何使用 XElement 检索属性的总和?
【发布时间】:2016-06-09 08:30:16
【问题描述】:

我一直在使用 XElement 来存储有关文件的信息,我希望能够对所有文件长度求和以获得文件的总大小。

我一直希望答案是这样的......

xmlDir.Elements("File").Attributes("Length").Sum();

我认为答案可能使用了 lambda 表达式,但我不知道如何构图。

我找到了告诉我如何对 XElement 中的元素求和的答案,但没有一个答案显示如何对属性的值求和。

<?xml version="1.0" encoding="utf-8"?>
<DirectoryDetails Path="F:\IndianSprings\Condensates" SerialNumber="10092693">
  <File Name="Start Menu\Programs\Games\Minesweeper.lnk" Length="1515" DateLastModified="2010-03-15T18:09:25.2325712-04:00" DateCreated="2010-08-16T05:11:39.171875-04:00" />
  <File Name="Start Menu\Programs\Games\Pinball.lnk" Length="885" DateLastModified="2010-03-15T18:09:25.2225568-04:00" DateCreated="2010-08-16T05:11:39.1875-04:00" />
  <File Name="Start Menu\Programs\Games\Solitaire.lnk" Length="1491" DateLastModified="2010-03-15T18:09:25.2325712-04:00" DateCreated="2010-08-16T05:11:39.21875-04:00" />
  <File Name="Start Menu\Programs\Games\Spider Solitaire.lnk" Length="1502" DateLastModified="2010-03-15T18:09:25.2425856-04:00" DateCreated="2010-08-16T05:11:39.515625-04:00" />
</DirectoryDetails>

【问题讨论】:

    标签: c# linq xelement


    【解决方案1】:

    你几乎明白了

    var result = xmlDir.Elements("File").Attributes("Length").Sum(a=>(int)a);
    

    a 是 XAttribute,XAttribute 支持显式转换为 int ((int)a)

    【讨论】:

    • 太棒了!现在,如果我能弄清楚为什么它会出现一个字节... LOL
    【解决方案2】:

    你可以试试这个 var v= xmlDir.Elements("File").Attributes("Length").Sum(x => (int)x);

    【讨论】:

      猜你喜欢
      • 2011-07-06
      • 2014-05-03
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      相关资源
      最近更新 更多