brinch
brinch

Reputation: 2614

How can I populate tuple using LINQ?

I have this xml block:

<difficulties>
    <difficulty difficultyId="1">
      <parameter key="maxNumerator" value="10"></parameter>
      <parameter key="maxDenominator" value="15"></parameter>
      <parameter key="couple" value="2"></parameter>
    </difficulty>
    <difficulty difficultyId="2">
      <parameter key="maxNumerator" value="20"></parameter>
      <parameter key="maxDenominator" value="30"></parameter>
      <parameter key="couple" value="2"></parameter>
    </difficulty>
    ...
</difficulties>

What I would like to do, is to fetch a pattern similar to:

difficultyId, key, value

like:

1, maxNumerator, 10
1, maxDenominator, 10
1, couple, 2
2, maxNumerator, 20
...

Is there some way I can insert it into a list of tuples (assuming I have loaded the xml document into xDocument already). I'd like to use LINQ:

List<Tuple<string, string, string>> res = from a in xDocument.Descendants("difficulties")
                                          ...?

Upvotes: 3

Views: 184

Answers (1)

ocuenca
ocuenca

Reputation: 39326

You can do a SelectMany:

 var res =(from a in xDocument.Descendants("difficulty")
           from parameter in a.Elements("parameter")
           select new Tuple<string,string,string>(a.Attribute("difficultyId").Value,
                                                  parameter.Attribute("key").Value,
                                                  parameter.Attribute("value").Value)).ToList();

Upvotes: 3

Related Questions