How can I get a List<int> from LINQ to XML that produces List<List<int>>?
I have an XML snippet as follows:
<PerformancePanel>
<LegalText>
<Line id="300" />
<Line id="304" />
<Line id="278" />
</LegalText>
</PerformancePanel>
I'm 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()
};
The type of LegalTextIds
is List<List<int>>
. How can I get this as a List<int>?
Don't create a new list for each item, just make one list:
LegalTextIds = (from legalText in panel.Elements("LegalText").Elements("Line")
select (int)legalText.Attribute("id")).ToList()
Use the 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()
};
How about this
List<int> GenListOfIntegers =
(from panel in doc.Elements("PerformancePanel").Elements("Line")
select int.Parse(panel.Attribute("id").Value)).ToList<int>();
精彩评论