2011-06-09 277 views
0

如果我有喜歡的xml:的LINQ to XML組查詢

<List> 
    <Item> 
    <Type>Type1</Type> 
    </Item> 
    <Item> 
    <Type>Type1</Type> 
    </Item> 
    <Item> 
    <Type>Type2</Type> 
    </Item> 
</List> 

我基本上要以某種方式創建一個字典或列表參閱下文此。這是我到目前爲止有:

var grouped = (from p in _xmlDoc.Descendants("Item") 
       group p by p.Element("Blah").Value into Items 
       select Items); 

我怎麼會選擇它,使我創造一個Dictionary<string, List<Item>>,其中關鍵是分組和(「類型1」或「2型」)的名稱。

回答

0
XDocument document = XDocument.Parse(xml); 

var query = (from item in document.Descendants("item") 
      select new 
      { 
       Key = (int)item.Value, 
       Value = (string)item.Descendants("type").Value 
      }).ToDictionary(pair => pair.Key, pair => pair.Value); 
-1
var grouped = (from p in _xmlDoc.Descendants("Item") 
       group p by p.Element("Blah").Value into Items 
       select Items).ToDictionary(g=>g.Key, g=>g.Value); 

類似的東西,你必須按正確的語法,但基本上,當你按的東西,你有鑰匙和價值過了,你可以用ToDictionary方法來此轉變成一本字典。

1

如果你不需要的物品隨機訪問,使用Lookup,這就是它的存在爲:

var lookup = _xmlDoc.Descendants("Item") 
    .ToLookup(e => (string)e.Element("Blah")); 

否則,如果您需要隨機訪問,然後把它們轉換成字典:

var dict = _xmlDoc.Descendants("Item") 
    .GroupBy(e => (string)e.Element("Blah")) 
    .ToDictionary(g => g.Key, g => g.ToList());