如何从LINQ获取List <int>生成List <list <int>&gt;的XML?</list <int> </int>

时间:2010-04-28 21:57:47

标签: c# xml linq linq-to-xml

我有一个XML代码段如下:

<PerformancePanel>
    <LegalText>
        <Line id="300" />
        <Line id="304" />
        <Line id="278" />
    </LegalText>
</PerformancePanel>

我正在使用以下代码来获取对象:

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

LegalTextIds的类型为List<List<int>>。我怎样才能将其作为List<int>?

3 个答案:

答案 0 :(得分:4)

不要为每个项目创建新列表,只需创建一个列表:

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

答案 1 :(得分:1)

使用SelectMany扩展名方法:

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

或者,就您的具体情况而言:

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

答案 2 :(得分:0)

这个怎么样

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