对 XElement 项进行分组 (Linq)
我有一个像这样构造的 XElement:
<items>
<item>
<param1>A</param1>
<param2>123</param2>
</item>
<item>
<param1>B</param1>
<param2>456</param2>
</item>
<item>
<param1>A</param1>
<param2>789</param2>
</item>
<item>
<param1>B</param1>
<param2>101112</param2>
</item>
</items>
我想获取一个字典,其中键绑定到
(A, B),值是相关项的列表:
A -> <item><param1>A</param1><param2>123</param2></item>
<item><param1>A</param1><param2>789</param2></item>
B -> <item><param1>B</param1><param2>456</param2></item>
<item><param1>B</param1><param2>101112</param2></item>
我尝试这样做:
var grouped = xItems.Descendants("item").GroupBy(r => r.Element("param1"))
.ToDictionary(g => g.Key, g => g.ToList());
但我仍然得到 4 个元素,一个带有重复键的键值集合,而不是我想要的 2 元素字典。有什么帮助吗?
I have an XElement structured like this:
<items>
<item>
<param1>A</param1>
<param2>123</param2>
</item>
<item>
<param1>B</param1>
<param2>456</param2>
</item>
<item>
<param1>A</param1>
<param2>789</param2>
</item>
<item>
<param1>B</param1>
<param2>101112</param2>
</item>
</items>
I want to obtain a dictionary where the keys are bound to <param1>
(A, B) and the value are lists of correlate items:
A -> <item><param1>A</param1><param2>123</param2></item>
<item><param1>A</param1><param2>789</param2></item>
B -> <item><param1>B</param1><param2>456</param2></item>
<item><param1>B</param1><param2>101112</param2></item>
I tried with this:
var grouped = xItems.Descendants("item").GroupBy(r => r.Element("param1"))
.ToDictionary(g => g.Key, g => g.ToList());
But I still get 4 elements, a key-value collection with duplicated keys, and not a 2 element dictionary as I'd like. Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该按每个元素的
.Value
属性而不是元素本身进行分组。这是因为元素总是不同的,因为它们实际上不是相同的元素,即使值相同。因此,您将为每个param1
元素获得一个组,无论其内容如何。试试这个:
这会打印出:
You should group by the
.Value
property of each element rather than the element itself. This is because the elements will always be different, as they aren't actually the same element, even if the values are the same. So you'll get a group for everyparam1
element, regardless of their contents.Try this instead:
This prints out:
好的,找到了。我忘记按元素的 VALUE 进行分组。以下作品:
Ok, found it. I forgot to group by the VALUE of the element. The following works: