4

Linq を使用して a Dictionary(またはさらに良い a ) を作成するにはどうすればよいですか?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現在、入力は私の関心事ではありません)、これを行うにはどうすればよいですか?

4

2 に答える 2

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);
于 2012-11-19T10:36:21.693 に答える
3

このようなことはします:

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

これはいつものことを生み出しましたDictionary; ConcurrentDictionary 通常Dictionaryのからを構築できます。


編集:これに気付いてくれた@spenderのおかげで、に変更Elementされました。Attributeそして「student」->「students」、@Jaroslawに感謝します。

于 2012-11-19T10:37:07.397 に答える