2016-06-09 66 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);