C# 使用 LinqToXml 使用过滤器选择唯一的 XElements(按属性)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/345025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:58:46  来源:igfitidea点击:

Select unique XElements (by attribute) with a filter using LinqToXml

c#xmllinq-to-xmlunique

提问by Mats

I have an XML document looking similar to this:

我有一个与此类似的 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>

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

现在我想使用 linq 查询获取属于指定类别的所有唯一所有者(我实际上只需要所有者的属性值)。在我的示例中,cat 1 的查询将返回一个包含 9 和 14 的列表。我该怎么做?Linq 语法比 Lambda 更受欢迎。提前致谢 ;)

采纳答案by Jennifer

Presuming the fragment is in itemsElement:

假设片段在 itemsElement 中:

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

Apologies for formatting and indentation!

为格式和缩进道歉!

回答by AnthonyWJones

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

}

回答by Theo

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