题
我有一个非常简单的Linq to XML查询:
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};
这适用于从PrimaryCategoryID 3的第一个CategoryList元素中提取categoryname和categoryURL。唯一的问题是PrimaryCategory中有多个CategoryList节点,我需要它返回一个可枚举的对象列表。中的名称和URL。
我做错了什么?
解决方案
如果您只希望有一个具有相关类别ID的PrimaryCategory元素,我会这样做:
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 };
你可以在一个查询中完成所有这些操作,但我认为将这两个位分开会更加混乱。
其他提示
虽然我将不同的答案标记为“the”回答我实际上用不同的方式解决了这个问题。即便如此,我也无法接受我自己的答案,而且JS完全有效并且很有帮助。所以作为除了我自己以外的唯一回答者,他的荣誉归于他。作为参考,我自己的解决方案包含在这里。
我最终确定的是:
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()};
然后我将结果提取到两个List对象并通过这些对象进行迭代。
不隶属于 StackOverflow