Search code examples
c#linqxelement

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


I've been using XElement to store information about files, and I would like to be able to sum all of the file lengths to get a total size of the files.

I keep wanting the answer to be something like this...

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

I think the answer probably uses a lambda expression, but I don't know how to frame it.

I've found answers that tell me how to sum elements in XElement, but none showing how to sum values of an attribute.

<?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>

Solution

  • you almost got it

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

    a is XAttribute and XAttribute supports explicit cast to int ((int)a)