linq到xml检查重复项,任意相等项

本文关键字:任意相 xml 检查 linq | 更新日期: 2023-09-27 18:24:02

我有xml文件

<Nodes>
   <Node> one </Node>
   <Node> two </Node>
   <Node> three </Node>
</Nodes>

在方法内部,我正在接收要附加到文件中的节点列表,所以我想检查是否有重复的

public static void AppendToXmlFile(List<string> passedNodes)
{
    bool duplicates = passedNodes.Any(x=>x.Equals(doc.Element("Nodes")
                                 .Descendants("Node")
                                 .Select(a=>a.Value))); 
...
}
this query always returns false.

linq到xml检查重复项,任意相等项

如果集合中有任何项,则

Any()将返回true。

为了实现你想要的,你可以这样做。

var duplicates = passedNodes.Descendants("Node").GroupBy(node=>node.Value).Any(grp=>grp.Count()>1);

您正在将passedNodes的元素xSelect返回的整个可枚举值进行比较。他们从不平等,因此总是错误的。你真的应该寻找两个列表的交集:

bool duplicates = doc.Element("Nodes")
                     .Descendants("Node")
                     .Select(a=>a.Value)
                     .Intersect(passedNodes)
                     .Any();

Any中的Select返回一个IEnumerable。这永远不会等于x(一个字符串)。试试这个

bool duplicates = passedNodes.Any(x => doc.Element("Nodes")
                             .Descendants("Node")
                             .Where(a => a.Value == x)
                             .Any());