基于属性值对递归子元素进行分组

时间:2011-04-26 06:25:56

标签: c# linq linq-to-xml

这是我的示例XML。如何使用LINQ to XML对这些Department元素进行分组,其中每个元素都具有属性hasLab='1'

   <ResearchLabs>
  <Departments>
    <Department  hasLab="1">
      <Department hasLab="0">
        <Subject name="Pharma"/>
        <Department hasLab="1">
          <Department hasLab="0">
            <Subject name="Data"/>
          </Department>
        </Department>
      </Department>
      <Department hasLab="0">
        <Subject name="Submission"/>
      </Department>
    </Department>
  </Departments>
</ResearchLabs>

2 个答案:

答案 0 :(得分:2)

目前尚不清楚你正在尝试做什么,但你可以使用:

var grouped = xml.Descendants("Department")
                 .GroupBy(x => (int) x.Attribute("hasLab"));

答案 1 :(得分:2)

这是你在找什么?

将所有没有实验室的子部门分组到具有实验室的父部门。

var query = from dept in doc.Descendants("Department")
            where (int)dept.Attribute("hasLab") == 0
               && dept.Parent.Name == "Department" // probably not needed
               && (int)dept.Parent.Attribute("hasLab") == 1
            group dept by dept.Parent;

或替代查询,可能更有效:

var query = from dept in doc.Descendants("Department")
            where (int)dept.Attribute("hasLab") == 1
            from sub in dept.Elements("Department")
            where (int)sub.Attribute("hasLab") == 0
            group sub by dept;

虽然我不想创建分组(肯定更有效率):

var query = from dept in doc.Descendants("Department")
            where (int)dept.Attribute("hasLab") == 1
            select new
            {
                Parent   = dept,
                Children = dept.Elements("Department")
                               .Where(sub => (int)sub.Attribute("hasLab") == 0),
            };