1

I'm having a hard time trying to create the query. This is the file:

<Root>
<Summary>
    <Objective ID="1">
        <Exam Result="70" />
        <Exam Result="90" />
    </Objective>
    <Objective ID="2">
        <Exam Result="100" />
        <Exam Result="90" />
    </Objective>
</Summary>
</Root>

I need to get the values in List< List< double>>. The first list if for objectives, and the last one is to store each result.

Any doubt, please let me know

H H
  • 263,252
  • 30
  • 330
  • 514
Darf
  • 2,495
  • 5
  • 26
  • 37

1 Answers1

6

I suspect you want:

var results = doc.Descendants("Objective")
                 .Select(x => x.Elements("Exam")
                               .Select(exam => (double) exam.Attribute("Result"))
                               .ToList())
                 .ToList();

Or if the objective ID is important, you might want to consider a Dictionary<int, List<double>>:

var results = doc.Descendants("Objective")
                 .ToDictionary(x => (int) x.Attribute("ID"),
                               x => x.Elements("Exam")
                                     .Select(y => (double) y.Attribute("Result"))
                                     .ToList());

Or a Lookup<int, double>:

var results = doc.Descendants("Exam")
                 .ToLookup(x => (int) x.Parent.Attribute("ID"),
                           x => x.Select(y => (double) y.Attribute("Result"));
Manuel
  • 12,749
  • 1
  • 27
  • 35
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Shouldn't there be a ',' rather than a '.' at the end of your .ToDictionary line? – Philipp Schmid Oct 17 '11 at 22:24
  • @PhilippSchmid: Yup - just a typo :) – Jon Skeet Oct 17 '11 at 22:25
  • @PhilippSchmid: In future, do go ahead - just leave a comment so I notice and can check :) – Jon Skeet Oct 17 '11 at 22:27
  • @Jon This is great. This is the the last question. How can I get a result grades? I mean, have a list ( List ) where contains the values of X objective. For example, if X = 1, it must get a list of results from objective 1. It would be contain, 70 and 80. – Darf Oct 17 '11 at 22:58
  • @OscarFimbres: With the dictionary version, you'd just use `List foo = results[1];`. – Jon Skeet Oct 17 '11 at 23:01
  • @JonSkeet: I took the liberty to correct a minor typo (Exame => Exam) – Manuel Oct 20 '11 at 11:47