2016-06-09 29 views
0

我一直在使用XElement來存儲有關文件的信息,我希望能夠總結所有文件長度以獲得文件的總大小。如何使用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> 

回答

2

你幾乎得到了它

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

a是XAttribute和XAttribute支持顯式的int(int)a

+0

非常好!現在,如果我能弄清楚爲什麼它出來了一個字節......大聲笑 –

1

你可以用這個 變種v嘗試= xmlDir.Elements(「文件「).Attributes(」Length「)。Sum(x =>(int)x);