简体   繁体   中英

Saving data from Linq-to-XML with groupBy to object List

I have an XML with this structure:

<weatherdata>
    <datapoint>
        <location>London</location>
        <rainfall>14</rainfall>
    </datapoint>
......
</weatherdata>

I would like to save the average rainfall grouped by location to Datapoint object List. Datapoint object has Location and AvgRainfall properties.

List<Datapoint> datapointList = new List<Datapoint>();
var q = xdoc.Element("weatherdata").Elements("datapoint")
       .GroupBy(e => e.Element("location").Value);

IEnumerable<Datapoint> d = xdoc.Element("weatherdata").Elements("datapoint")
  .GroupBy(e => e.Element("location").Value)
  .Select(x => new Datapoint
   {
      RegionName = x.Key,
      AvgRainfall = x.Select(e => e.Elements("rainfall")
                 .Average(f => double.Parse(f.Value)))
   });

The problem is, that AvgRainfall property is a double, but the x.Select returns an IEnumerable - double - list. Kindly point me to the right direction.

edit: this solution worked well for my problem:

AvgRainfall = x.Elements("rainfall").Average(f => double.Parse(f.Value)) 

Try this:

AvgRainfall = x.SelectMany(e => e.Elements("rainfall").Select(f => f.value))
             .Average(g => double.Parse(g))

SelectMany returns list of specific elements from multiple collections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM