簡體   English   中英

如何使用XElement檢索屬性的總和?

[英]How can I use XElement to retrieve the Sum of an Attribute?

我一直在使用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>

你幾乎明白了

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

a是XAttribute並且XAttribute支持顯式轉換為int(int)a

您可以嘗試使用此var v = xmlDir.Elements(“ File”)。Attributes(“ Length”)。Sum(x =>(int)x);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM