0

I have xml file

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

inside method I'm receving list of nodes to append into file, so I want to check is there duplicates

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.
user1765862
  • 13,635
  • 28
  • 115
  • 220

3 Answers3

2

Any() will return true if the collection has any items.

To achieve what you want you can do this.

var duplicates = passedNodes.Descendants("Node").GroupBy(node=>node.Value).Any(grp=>grp.Count()>1);
Tormod
  • 4,551
  • 2
  • 28
  • 50
1

Your Select inside the Any returns a IEnumerable. This will never be equal to x (a string). Try with this

bool duplicates = passedNodes.Any(x => doc.Element("Nodes")
                             .Descendants("Node")
                             .Where(a => a.Value == x)
                             .Any());
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
1

You are comparing element x of passedNodes with the whole enumerable returned by Select. They are never equal, hence always false. You should really be looking for intersection of two lists instead:

bool duplicates = doc.Element("Nodes")
                     .Descendants("Node")
                     .Select(a=>a.Value)
                     .Intersect(passedNodes)
                     .Any();
Andrei
  • 55,890
  • 9
  • 87
  • 108