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


Don't create a new list for every item, just create one list:



LegalTextIds = (from legalText in panel.Elements("LegalText").Elements("Line")
                select (int)legalText.Attribute("id")).ToList()

      

+4


a source


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


How about this

List<int> GenListOfIntegers = 
          (from panel in doc.Elements("PerformancePanel").Elements("Line")
              select int.Parse(panel.Attribute("id").Value)).ToList<int>();

      

0


a source







All Articles