使用Linq创建一个字典

时间:2012-11-19 10:29:42

标签: c# linq dictionary concurrentdictionary

如何使用Linq创建Dictionary(甚至更好,ConcurrentDictionary)?

例如,如果我有以下XML

<students>
    <student name="fred" address="home" avg="70" />
    <student name="wilma" address="home, HM" avg="88" />
    .
    . (more <student> blocks)
    .
</students>

加载到XDocument doc;并希望填充ConcurrentDictionary<string, Info>(其中键是名称,而Info是一个持有地址和平均值的类。填充Info不是我的现在关注),我该怎么做?

2 个答案:

答案 0 :(得分:9)

XDocument xDoc = XDocument.Parse(xml);
var dict = xDoc.Descendants("student")
                .ToDictionary(x => x.Attribute("name").Value, 
                              x => new Info{ 
                                  Addr=x.Attribute("address").Value,
                                  Avg = x.Attribute("avg").Value });


var cDict = new ConcurrentDictionary<string, Info>(dict);

答案 1 :(得分:3)

这样的事情会:

var dict = xml.Descendants("student")
              .ToDictionary(r => (string)r.Attribute("name").Value, r => CreateInfo(r));

这只产生了Dictionary;您可以构建ConcurrentDictionary from the usual Dictionary


修改:将Element更改为Attribute,感谢@spender注意到这一点。和“学生” - &gt; “学生”,感谢@Jaroslaw。

相关问题