<states_Page>
<states>
<state id="sectionenable" systemstate="n" focuscontrol="" default="">
</state>
</states>
<states>
<state id="controlenable" systemstate="n" focuscontrol="" default="">
</state>
</states>
<states>
<state id="controldisable" systemstate="n" focuscontrol="" default="">
</state>
</states>
<states>
<state id="controldisable2" systemstate="n" focuscontrol="" default="">
</state>
</states>
<states>
<state id="sectionenable2" systemstate="n" focuscontrol="" default="">
</state>
</states>
<states>
<state id="sectionenable" systemstate="n" focuscontrol="" default="">
</state>
</states>
</states_Page>
根元素下有6个元素..
我想要具有不同属性名称的节点。
所以我只需要返回5个具有不同属性值的元素。 我尝试了一个linq,但它只返回不同的属性值..但我需要整个元素。
var ds = (from ele in root.Elements("states").Elements("state")
select ele.Attribute("id").Value).Distinct();
帮助我在单行查询中获取整个元素。
答案 0 :(得分:0)
试试这个: -
var result = xdoc.Root.Descendants("states")
.GroupBy(x => x.Element("state").Attribute("id").Value)
.Select(x => x.First());
如果要获取元素而不是节点,可以使用anonymous
类型: -
var result = xdoc.Root.Descendants("states")
.GroupBy(x => x.Element("state").Attribute("id").Value)
.Select(x =>
{
var firstNode = x.First().Element("state");
return new
{
StateId = firstNode.Attribute("id").Value,
SystemState = firstNode.Attribute("systemstate").Value,
Focuscontrol = firstNode.Attribute("focuscontrol").Value,
Default = firstNode.Attribute("default").Value
};
});