2012-11-19 45 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