views:

2501

answers:

4

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

A: 

How can you do LINQ without lambdas? Lambdas are a key element of LINQ. What's wrong with lambdas?

Theo
I presume he means from x in y select x.z rather than y.select(x=>x.z) ;Personally I prefer the latter!
Jennifer
+4  A: 

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!

Jennifer
Or in 'lambda' form:itemElements.Where(x=>x.Attribute("cat")==1).Select(x=>x.Attribute("owner")).Distinct();Personally I prefer that!
Jennifer
'itemElements' should be 'item' in where clause. Attribute method returns an XAttribute which cannot be compared with 1 using == needs a cast to int and Distinct for cat="2" will still return 2 items since both attributes are each a distinct object.
AnthonyWJones
... so apart from the glaring syntax errors and my complete lack of xlinq knowledge, I am competely on the money. Wonder if there is any way of down-voting your own posts...
Jennifer
+1  A: 

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

}
AnthonyWJones
A: 
  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();
Theo