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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With