2012-11-19 123 views
3

如何使用Linq创建Dictionary(或更好,ConcurrentDictionary)?使用Linq创建词典

举例来说,如果我有以下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不我现在的担忧),我该怎么做?

+1

是“使用LINQ”的一个要求还是趋势? – Vlad

+1

可能的重复:http://stackoverflow.com/questions/1710193/converting-an-xml-document-to-a-dictionary – Christian

+2

@Vlad这是一个趋势 – baruch

回答

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); 
+0

是的,我看到,只是重新检查文档。 – Vlad

+0

如果'ConcurrentDictionary'是必须的,则最好跳过'.ToDictionary'并直接将序列加载到'foreach'循环中的空'ConcurrentDictionary'中。这将避免创建一个被丢弃的'Dictionary'('dict')。 – spender

3

像这样的东西会做:

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

这只是产生了平常Dictionary;你可以构建一个ConcurrentDictionaryfrom the usual Dictionary


编辑:改变ElementAttribute,感谢@spender用于察觉这一点。还有“学生” - >“学生”,感谢@Jaroslaw。

+0

你测试过了吗? – jwaliszko

+0

@Jaroslaw:不,实际上 - 有问题吗?如果是的话,你可以帮助改善答案(或给你自己的答案)。 – Vlad

+0

是的,有一个错误,请解决这个问题。 – jwaliszko