tags:

views:

96

answers:

1

Hey there!

I have an XML file similar to the following:

<novel>
  <paragraphs>
     <paragraph>
         <choice>This is paragraph 1</choice>
         <choice>Paragraph 1 alternative text</choice>
     </paragraph>
     <paragraph>
         <choice>This is paragraph 2</choice>
         <choice>Paragraph 2 alternative text</choice>
     </paragraph>
  </paragraphs>
</novel>

And I'm reading this into my program using LINQ. I am still learning LINQ. I'd like to have a 2-d array mapping of paragraphs and choices, ie Paragraph[0][0] = "This is paragraph 1" and Paragraph[1][1] = "Paragraph 2 alternative text".

The problem is I am unsure how to nest these arrays within LINQ. At the minute I have:

var paragraphsQuery =
   from paragraphsNode in xDoc.Elements("novel").Elements("paragraphs")
   from choiceNodes in paragraphsNode.Elements("paragraph").Elements("choice")
   select choiceNodes.Value;

...but this gives me one array of all the choices combined (I have lost the paragraph segregations). It seems somehow I need to do more from statements within the select?

Could anyone offer me any advice? Thank you.

+2  A: 

You need something like:

var paragraphsQuery = xDoc.Elements("novel")
                          .Elements("paragraphs")
                          .Elements("paragraph")
                          .Select(p => p.Elements("choice")
                                        .Select(c => c.Value)
                                        .ToList())
                          .ToList();

In other words, at the top level you want one item per "paragraph" element. Then for each item, you want to find the values of the "choice" elements, and turn them into a list.

(That will use lists rather than arrays - you could use arrays if you really want, but lists are usually simpler to work with.)

Jon Skeet
Lists are larger, slower and more mutable than arrays - and adding or removing elements to complex query results is something I have never yet needed. Why not stick with the lower-weight and better-behaving arrays?
Eamon Nerbonne
Many thanks, works just how I wanted!
DanDan
@Eamon: See http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx
Jon Skeet
Also, when it comes to "slower" - calling ToArray can cause more copying to be done than ToList. As for "better-behaving" - the variance available on reference type arrays, the fact that there are operations like Add and Remove which are available but throw at execution time... none of that strikes me as "better-behaving".
Jon Skeet