查找重复的 xelements [英] Find duplicate xelements

查看:19
本文介绍了查找重复的 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 查询.在上面的 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 中重复的 Cars 条目列表,您可以从那里获取:

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

这篇关于查找重复的 xelements的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆