2011-06-09 278 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());