找到重复的元素 [英] Find duplicate xelements
问题描述
我有以下XML
<Automobiles>
<Cars>
<YearofMfr>2010</YearofMfr>
<Mileage>12</Mileage>
<MeterReading>1500</MeterReading>
<Color>Red</Color>
<Condition>Excellent</Condition>
</Cars>
<Cars>
<YearofMfr>2010</YearofMfr>
<Mileage>12</Mileage>
<MeterReading>1500</MeterReading>
<Color>Red</Color>
<Condition>Excellent</Condition>
</Cars>
<Cars>
<YearofMfr>2008</YearofMfr>
<Mileage>11</Mileage>
<MeterReading>20000</MeterReading>
<Color>Pearl White</Color>
<Condition>Good</Condition>
</Cars>
</Automobiles>
我正在寻找一个返回重复节点的LINQ Query。在上面的XML中有两个类似的节点。结果应该包括重复的节点。
I was looking for a LINQ Query which would return duplicate nodes. In the above XML there are two nodes which are similar. The result should include both the duplicate nodes.
我还需要一个查询,返回所有不重复的节点。请帮助。
I also need a query which would return all the nodes which are not duplicate. Please help.
推荐答案
此查询将导致重复的汽车列表
你的XML中的条目,你可以从那里获取:
This query would result in the list of duplicate Cars
entries in your XML, you could take it from there:
XDocument doc = XDocument.Load(@"test.xml");
var duplicates = doc.Descendants("Cars")
.GroupBy(c => c.ToString())
.Where(g => g.Count() > 1)
.Select(g => g.First())
.ToList();
列表中的每个副本都不包含多个节点,重复。同样地,您可以滤除与其他任何Cars节点重复的不节点,只需更改where条件:
There's no point in including more than one node for each duplicate in the list because..well they're duplicates. Similarly you can filter out the nodes that are not duplicates with any other Cars node, just change the where condition:
var uniqueCars = doc.Descendants("Cars")
.GroupBy(c => c.ToString())
.Where(g => g.Count() == 1)
.Select(g => g.First())
.ToList();
这篇关于找到重复的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!