Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LinqToXml:解析到字典_C#_Linq - Fatal编程技术网

C# LinqToXml:解析到字典

C# LinqToXml:解析到字典,c#,linq,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'></

我有以下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>
第一个参数是xml中的
Type
,第二个参数是此类型的计数


谢谢。

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元素”是有误导性的-字典没有可靠的顺序:您不应该假设如果迭代键/值对,您将以任何特定的顺序看到它们。

查询语法

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

我不明白如何把它编入字典
 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());