views:

93

answers:

3

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>?

+4  A: 

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()
Mark Byers
+1  A: 

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()
};
Dathan
A: 

How about this

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