tags:

views:

92

answers:

2

I have a pretty simple Linq to XML query:

var q = from c in xd.Descendants("PrimaryCategory")
        where (int)xd.Element("PrimaryCategoryID") == 3
        select new {campaignName = c.Element("CategoryList").Element("CategoryName").Value,
        campaignURL = c.Element("CategoryList").Element("CategoryURL").Value};

This does fine for pulling the categoryname and the categoryURL from the first CategoryList element of the PrimaryCategoryID 3. The only problem is that there are multiple CategoryList nodes in the PrimaryCategory and I need it to return an enumerable list of objects with all of the Names and URLs in.

What am I doing wrong?

A: 

If you only expect there to be a single PrimaryCategory element with the relevant category ID, I'd do:

var category = xd.Descendants("PrimaryCategory")
                 .Where(c => (int)c.Element("PrimaryCategoryID") == 3)
                 .Single(); // Could use `FirstOrDefault` if there could be none

var query = from list in category.Elements("CategoryList")
            select new { Name = list.Element("CategoryName").Value,
                         Url = list.Element("CategoryURL").Value };

You could do all of this in a single query, but I think it would be more confusing than splitting the two bits up.

Jon Skeet
+1  A: 

Although I Marked a different answer as "the" answer I actually solved this problem a different way. Even so I get nothing for accepting my own answer and JS's is perfectly valid and was helpful. So as the sole answerer besides myself the kudos goes to him. For reference my own solution is included here.

What I eventually settled on was:

var xmlcampaigns = from c in xd.Descendants("PrimaryCategory")
                   where (int)c.Element("PrimaryCategoryID") == 3
                   select new {campaignName = c.Elements("CategoryList").Elements("CategoryName").ToList(),
                   campaignURL = c.Elements("CategoryList").Elements("CategoryURL").ToList()};

I then extracted the results to two List objects and iterated through those.