使用LinqToXml通过属性筛选选择唯一的XElements

7

我有一个类似于以下的XML文档:

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

现在我想使用Linq查询来获取属于特定类别的所有唯一所有者(实际上我只需要所有者的属性值)。在我的示例中,对于类别1的查询将返回一个包含9和14的列表。我该怎么做? Linq语法优先于Lambdas。谢谢!

3个回答

15

假设该片段位于itemsElement中:

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

抱歉格式和缩进有误!


1
或者用'lambda'形式: itemElements .Where(x=>x.Attribute("cat")==1) .Select(x=>x.Attribute("owner")) .Distinct();个人而言,我更喜欢这种方式! - Jennifer
'itemElements' 应该在 where 子句中改为 'item'。Attribute 方法返回的是 XAttribute,不能使用 == 与 1 进行比较,需要将其转换为 int 类型,而对于 cat="2" 的 Distinct 仍会返回 2 个项目,因为这两个属性各自是独立的对象。 - AnthonyWJones
1
除了明显的语法错误和我完全不懂xlinq的知识之外,我完全正确。不知道有没有办法对自己的帖子进行投票... - Jennifer

2
尝试使用这个函数:-
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();

}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接