简体   繁体   中英

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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM