tags:

views:

68

answers:

2

I am curious if there is a way where I can capture the lower lines (the creation of the dictionary and loop to add values) in the linq statement itself. Right now the select new returns a new anonymous type but I am wondering if there is a way to make it return a Dictionary with all the values pre-populated.

    XDocument reader = XDocument.Load("sl.config");
    var configValues = from s in reader.Descendants("add") select new { Key = s.Attribute("key").Value, s.Attribute("value").Value };

    Dictionary<string, string> Settings = new Dictionary<string, string>();

    foreach (var s in configValues)
    {
        Settings.Add(s.Key, s.Value);
    }
+6  A: 

Try Enumerable.ToDictionary extension method.

 XDocument reader = XDocument.Load("sl.config");
 var Settings = reader.Descendants("add")
   .ToDictionary(s => s.Attribute("key").Value, s => s.Attribute("value").Value);
Denis Krjuchkov
It should be `Dictionary<string, string> Settings =` rather than `var configValues =`
Gabe
Yep, fixed variable name, thanks ;-)
Denis Krjuchkov
Thanks for that!
keithwarren7
+2  A: 
var = XDocument.Load("sl.config").Descendants("add").ToDictionary
    (x => x.Attribute("key"). Value, x => x.Attribute("value"). Value);
Paul Creasey
I hope you don't mind that i formatted a bit. :)
Arnis L.