Multi-dimensional arrays in Linq
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.
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.)
精彩评论