c# - Using LINQ to parse XML into Dictionary -
i have configuration file such as:
<configurationfile> <config name="some.configuration.setting" value="some.configuration.value"/> <config name="some.configuration.setting2" value="some.configuration.value2"/> ... </configurationfile>
i trying read xml , convert dictionary. tried coding liek wrong not compile.
dictionary<string, string> configdictionary = (from configdatum in xmldocument.descendants("config") select new { name = configdatum.attribute("name").value, value = configdatum.attribute("value").value, }).todictionary<string, string>(something shoudl go here...?);
if tell me how working helpful. always, of course, read
to give more detailed answer - can use todictionary
wrote in question. in missing part, need specify "key selector" , "value selector" these 2 functions tell todictionary
method part of object you're converting key , value. extracted these 2 anonymous type, can write:
var configdictionary = (from configdatum in xmldocument.descendants("config") select new { name = configdatum.attribute("name").value, value = configdatum.attribute("value").value, }).todictionary(o => o.name, o => o.value);
note removed generic type parameter specification. c# compiler figures automatically (and we're using overload 3 generic arguments). however, can avoid using anonymous type - in version above, create temporary store value. simplest version just:
var configdictionary = xmldocument.descendants("config").todictionary( datum => datum.attribute("name").value, datum => datum.attribute("value").value );
Comments
Post a Comment