Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Dictionary using Linq

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?

like image 874
Baruch Avatar asked Dec 15 '22 17:12

Baruch


1 Answers

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);
like image 83
L.B Avatar answered Dec 30 '22 14:12

L.B