我有一个类似于此的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查询获取属于指定类别的所有唯一所有者(实际上只需要所有者的属性值)。在我的示例中,cat 1的查询将返回包含9和14的列表。我该怎么做? Linq语法比Lambdas更受欢迎。在此先感谢;)
答案 0 :(得分:15)
假设片段在itemsElement:
中var distinctOwners = (from item in itemsElement.Element("item")
where itemElements.Attribute("cat") == 1
select item.Attribute("owner")).Distinct();
格式化和缩进的道歉!
答案 1 :(得分: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();
}
答案 2 :(得分: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();