Pergunta

How can I create a Dictionary (or even better, a ConcurrentDictionary) using Linq?

For example, if I have the following XML

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

loaded into XDocument doc; and wanted to populate a ConcurrentDictionary<string, Info> (where the key is the name and Info is some class holding address and average. Populating Info is not my concern now), how would I do this?

Foi útil?

Solução

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

Outras dicas

Something like this will do:

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

This produced just a usual Dictionary; you can construct a ConcurrentDictionary from the usual Dictionary.


Edit: changed Element to Attribute, thanks to @spender for noticing this. And "student" -> "students", thanks to @Jaroslaw.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top