LinQ GroupBy对具有相同属性的嵌套元素

何塞3d

我有以下xml输出:

<R N="1">
  <MT N="Section" V="Section-1" />
  <MT N="Person" V="John" />
</R>
<R N="2">
  <MT N="Section" V="Section-1" />
  <MT N="Person" V="Peter" />
</R>
<R N="3">
  <MT N="Section" V="Section-2" />
  <MT N="Person" V="Joseph" />
</R>

……

<R N="N">
  <MT N="Section" V="Section-J" />
  <MT N="Person" V="PersonX" />
</R>

我试图组成一个LinQ查询来按节将所有结果分组,使用节值作为键,将整个元素用作元素选择器:

//MyElements its an IEnumerable<XElement>
var something = MyElements.GroupBy
(
   x => x.Elements("MT")
   .Where
   (
     type => type.Attribute("N").Value == "Section"
   )
   .Select
   (
     type => type.Attribute("V").Value
   )
   ,
   x=>x
);

当我调试我的东西变量不包含元素。

有什么建议吗?

提前致谢。

约瑟

乔恩

按键选择最终会出现一个IEnumerable<string>结果,这肯定是错误的。它应该给您一个平淡的string,可实现的

x => x.Elements("MT").Single(t => t.Attribute("N").Value == "Section")
                     .Attribute("V").Value

您也不需要身份投影x => x,这是隐含的。

最后,如果代码本身不是空的,则给出的代码将永远不会导致something空的可枚举MyElements

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章