Multilpe object initializers in 1 LINQ query
I was wondering how I could select multiple object initializers in 1 select statement using an XML document. I would like to avoid multiple iterations on the same file.
The XML structure looks like this:
<root>
<doc name="test.doc">
<version lang="nl">
</version>
<version lang="fr">
</version>
</doc>
<doc name="test2.doc">
<version lang="nl">
<title>Document over ons</title>
</version>
<version lang="fr">
<title>Document de nous</title>
</version>
</doc>
</root>
The LINQ statement for 1 element would look like this:
var docs = select e from xmlDoc.Descendants("doc")
select new docEntry()
{
Name = (string)e.Attribute("name"),
Title = (string)element.Elements("version").Where(d => (string)d.Attribute("language_code") == "nl").First().Element("title")
}
Now I would like to select the french version in 1 go as well, pseudo code something like this:
var docs = select e from xmlDoc.Descendants("doc")
select new docEntry()
{
Name = (string)e.Attribute("name"),
Title = (string)element.Elements("version").Where(d => (string)d.Attribute("language_code") == "nl").First().Element("title")
},
select new docEntry()
{
Name = (string)e.Attribute("name"),
Title = (string)element.Elements("version").Where(d => (string)d.Attribute("language_code") == "fr").First().Element("title")
}
Any ideas on how I can accomplish this in 1 go? I know I could do this in 2 round trips 开发者_开发问答through the XML but that would be stupid, no?
var docs = from e in xmlDoc.Descendants("doc")
select new
{
NL = new docEntry
{
Name = e.Attribute("name").Value,
Title = e.Elements("version").Where(d => d.Attribute("language_code").Value == "nl").First().Element("title").Value
},
FR = new docEntry
{
Name = e.Attribute("name").Value,
Title = e.Elements("version").Where(d => d.Attribute("language_code").Value == "fr").First().Element("title").Value
}
};
Another, slightly different option :
var docs = from e in from xmlDoc.Descendants("doc")
select new[]
{
new docEntry
{
Name = e.Attribute("name").Value,
Title = e.Elements("version").Where(d => d.Attribute("language_code").Value == "nl").First().Element("title").Value
},
new docEntry
{
Name = e.Attribute("name").Value,
Title = e.Elements("version").Where(d => d.Attribute("language_code").Value == "fr").First().Element("title").Value
}
};
精彩评论