XDocument to Dictionary

bal*_*aji 0 c# linq linq-to-xml

这是我的Xdocument:

<Response>
    <city>
        <CityName>xxx</CityName>
        <CityId>1</CityId>
    </city>
    <city>
        <CityName>yyy</CityName>
        <CityId>2</CityId>
    </city>   
</Response>
Run Code Online (Sandbox Code Playgroud)

我如何将其存储在Dictionary(cityname,cityid):

Dictionary<string, string > dictionary;
Run Code Online (Sandbox Code Playgroud)

Mar*_*zek 5

var doc = XDocument.Load(filePath);
var dict = doc.Root.Elements("city")
                   .ToDictionary(c => (string)c.Element("CityName"),
                                 c => (string)c.Element("CityId"));
Run Code Online (Sandbox Code Playgroud)

棘手的问题 - 为什么你想要CityId一个字符串,而不是一个int