Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select unique XElements (by attribute) with a filter using LinqToXml

I have an XML document looking similar to this:

<items>
 <item cat="1" owner="14">bla</item>
 <item cat="1" owner="9">bla</item>
 <item cat="1" owner="14">bla</item>
 <item cat="2" owner="12">bla</item>
 <item cat="2" owner="12">bla</item>
</items>

Now I'd like to get all unique owners (I actually only need the attribute value of the owner) belonging to a specified category using a linq query. In my example, the query for cat 1 would return a list containing 9 and 14. How can I do that? Linq syntax would be preferred over Lambdas. Thanks in advance ;)

like image 831
Mats Avatar asked Dec 05 '08 20:12

Mats


1 Answers

Presuming the fragment is in itemsElement:

var distinctOwners = (from item in itemsElement.Element("item") 
 where itemElements.Attribute("cat") == 1 
select item.Attribute("owner")).Distinct();

Apologies for formatting and indentation!

like image 86
Jennifer Avatar answered Nov 11 '22 04:11

Jennifer