我有一个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的语法将在Lambda表达式是首选。由于事先;)

有帮助吗?

解决方案

。假定该片段是在itemsElement:

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

道歉格式和缩进!

其他提示

尝试这样的功能: -

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

}
  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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top