LinqToXml:解析为字典

时间:2012-05-15 05:41:04

标签: c# linq

我有以下xml:

<Places Count='50'>
<Place ID='1' Row='1' Place='1' Type='1' Fragment='0'></Place>
<Place ID='2' Row='1' Place='2' Type='1' Fragment='0'></Place>
<Place ID='3' Row='1' Place='3' Type='2' Fragment='0'></Place>
<Place ID='4' Row='1' Place='4' Type='2' Fragment='0'></Place>
<Place ID='5' Row='1' Place='5' Type='2' Fragment='0'></Place>
//other tags
</Places>

我希望Dictionary<int, int>获得以下内容:

1,2  // 0 element in the Dictionary (type =1; count = 2)
2,3; // 1 element in the Dictionary (type =2; count = 3)

第一个参数是xml中的Type,第二个参数是此类型的计数。

感谢。

2 个答案:

答案 0 :(得分:6)

LINQ to XML结合LINQ to Objects使这非常简单:

var dictionary = doc.Descendants("Place")
                    .GroupBy(x => (int) x.Attribute("Type"))
                    .ToDictionary(g => g.Key, g => g.Count());

它没有那么高效,但我坚持这个实现,直到我发现它成为一个问题。

请注意,在字典中讨论“0元素”会产生误导 - 字典没有可靠的排序:你不应该假设如果你遍历键/值对,你会以任何特定的顺序看到它们。 / p>

答案 1 :(得分:1)

查询语法

 var dict = (from place in root.Descendants("Place")
       group place by (int)place.Attribute("Type") into g
        select g).ToDictionary(g=>g.Key, g=>g.Count());