Find duplicate xelements

孤者浪人 提交于 2019-12-18 09:27:33

问题


I have the below 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>

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.


回答1:


I suggest, you create a Car class and create a list of Car instances from the XML and do your analysis on that list.
It would simplify things, because you could overwrite the Equals method of the Car class to only return true, if all properties are the same.




回答2:


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();

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();


来源:https://stackoverflow.com/questions/5076772/find-duplicate-xelements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!