在Linq中按键打印

时间:2014-07-20 10:55:14

标签: c# linq

我有一个看起来像这样的XElement集合:

XElement teachers = new XElement("Teachers",
new XElement("Teacher",
    new XAttribute("Id", 1),
    new XAttribute("Age", 50)
),
new XElement("Teacher",
    new XAttribute("Id", 2),
    new XAttribute("Age", 60)
),
new XElement("Teacher",
    new XAttribute("Id", 3),
    new XAttribute("Age", 50)
)
);

我想按年龄分组。

我在理解查询语法中编写的查询是:

var initials = from t in teachers.Elements()
    let age = teachers.Attribute("Age")
    group t by age
    into ageGroups
    orderby ageGroups.Key descending
    select ageGroups;

这是我用来获取输出的代码:

foreach (var initial in initials)
{
    Console.WriteLine(initial.Key);
    foreach (var element in initial)
    {
        Console.WriteLine(element.Name.ToString() + element.Attribute("Id").ToString());
    }
}

但我得到的是

TeacherId="1"
TeacherId="2"
TeacherId="3"

没有任何年龄。我调试了代码,年龄组为null。代码有什么问题?

1 个答案:

答案 0 :(得分:3)

这应该有效

var initials = from t in teachers.Elements()
    let age = t.Attribute("Age").Value
    group t by age
    into ageGroups
    orderby ageGroups.Key descending
    select ageGroups;

您的代码无效,因为您正在调用没有任何属性的teachers.Attribute("Age"),您需要在每个Teacher元素中调用它。