Mats
Mats

Reputation: 14817

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 ;)

Upvotes: 7

Views: 20209

Answers (3)

AnthonyWJones
AnthonyWJones

Reputation: 189505

Try this function:-

static IEnumerable<int> GetOwners(XDocument doc, string cat)
{
    return from item in doc.Descendants("item")
        where item.Attribute("cat").Value == cat
        select (int)item.Attribute("owner")).Distinct();

}

Upvotes: 2

Theo
Theo

Reputation: 452

  XElement ele = XElement.Parse(@"<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>");

  int cat = 1;


  List<int> owners = ele.Elements("item")
    .Where(x=>x.Attribute("cat").Value==cat.ToString()).Select(x=>Convert.ToInt32(x.Attribute("owner").Value)).Distinct().ToList();

Upvotes: 0

Jennifer
Jennifer

Reputation: 5218

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!

Upvotes: 15

Related Questions