Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for Duplicate Values in Each Child in XML via LINQ

Tags:

c#

xml

linq

I'm new to using linq in particular linq to xml and am having trouble trying to iterate through the results. My xml document has multiple nodes of the same name nested in a single parent node.

Sample XML is :

<commercial>
   <listingAgent>1</listingAgent>
   <listingAgent>2</listingAgent>
   <listingAgent>1</listingAgent>
</commercial>  
<commercial>
   <listingAgent>1</listingAgent>
   <listingAgent>2</listingAgent>
   <listingAgent>3</listingAgent>
</commercial> 

So for each commercial tag there should be unique listing agent values. If not i need to raise an error.

The real XML is extremely complicated and these tags are nowhere near root. So i need to traverse to these and then search for duplciates

I tried the following code

foreach (XElement e in root.Descendants("listingAgent"))
{
   listerror.Add(e.Value);
}

if(listerror.Count != listerror.Distinct().Count()) 
     Then show error

But i need this looping to be done for each commercial.

like image 404
Bhumika Sanghvi Avatar asked Dec 01 '25 06:12

Bhumika Sanghvi


1 Answers

First, select all the commercial nodes, then for each node you can get the list of agents values using a Select, this way you will get a list of list, and finally you can apply the same condition you try before, but now for each list of agents:

var result= xdoc.Descendants("commercial")
                .Select(c=>c.Descendants("listingAgent").Select(e=>e.Value));
if(result.Any(e=>e.Count()!= e.Distinct().Count())
{
  //error
}
like image 179
octavioccl Avatar answered Dec 03 '25 18:12

octavioccl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!