How can I get a List <int> from LINQ to XML that creates a List <List <int>>?
I have an XML snippet like this:
<PerformancePanel>
<LegalText>
<Line id="300" />
<Line id="304" />
<Line id="278" />
</LegalText>
</PerformancePanel>
I am using the following code to get an object:
var performancePanels = new
{
Panels = (from panel in doc.Elements("PerformancePanel")
select new
{
LegalTextIds = (from legalText in panel.Elements("LegalText").Elements("Line")
select new List<int>()
{
(int)legalText.Attribute("id")
}).ToList()
}).ToList()
};
Type LegalTextIds
- List<List<int>>
. How can I get this likeList<int>?
+2
a source to share
3 answers
Use SelectMany
extension method:
List<List<int>> lists = new List<List<int>>()
{
new List<int>(){1, 2},
new List<int>(){3, 4}
};
var result = lists.SelectMany(x => x); // results in 1, 2, 3, 4
Or for your specific case:
var performancePanels = new
{
Panels = (from panel in doc.Elements("PerformancePanel")
select new
{
LegalTextIds = (from legalText in panel.Elements("LegalText").Elements("Line")
select new List<int>()
{
(int)legalText.Attribute("id")
}).SelectMany(x => x)
}).ToList()
};
+1
a source to share