選択なXElements(属性)フィルターを使用LinqToXml
-
19-08-2019 - |
質問
私は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.よろしくお願;)
解決
仮に、フラグメントに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();
所属していません StackOverflow