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
  • 12,589
  • 27
  • 102
  • 186

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,437
  • 2
  • 27
  • 48
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
  • 65,896
  • 14
  • 126
  • 152
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
  • 54,517
  • 9
  • 84
  • 106