代码之家  ›  专栏  ›  技术社区  ›  DaveDev

如何从linq到xml获取一个生成list的list<int>?

  •  2
  • DaveDev  · 技术社区  · 14 年前

    我有一个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 回复  |  直到 14 年前
        1
  •  4
  •   Mark Byers    14 年前

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

    LegalTextIds = (from legalText in panel.Elements("LegalText").Elements("Line")
                    select (int)legalText.Attribute("id")).ToList()
    
        2
  •  1
  •   Dathan    14 年前

    使用 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()
    };
    
        3
  •  0
  •   Asad    14 年前

    这个怎么样?

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