2008-12-05 69 views
7

我有一個XML文檔,尋找一個類似的過濾器,選擇獨特的XElements(按屬性):使用LinqToXml

<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更受歡迎。在此先感謝;)

回答

15

。假定該片段是在itemsElement:

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

道歉格式和縮進!

+1

或者在 '拉姆達' 形式: itemElements 。凡(X => x.Attribute( 「貓」)== 1) 。選擇( x => x.Attribute(「owner」)) .Distinct(); 我個人更喜歡那個! – Jennifer 2008-12-05 20:58:02

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