LinqToXml:解析为字典

use*_*827 0 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>
Run Code Online (Sandbox Code Playgroud)

我想得到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)
Run Code Online (Sandbox Code Playgroud)

第一个参数是Typexml,第二个参数是这种类型的计数.

谢谢.

Jon*_*eet 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());
Run Code Online (Sandbox Code Playgroud)

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

请注意,在字典中讨论"0元素"会产生误导 - 字典没有可靠的排序:您不应该假设如果迭代键/值对,您将以任何特定顺序看到它们.