Using LINQ to parse XML in a dictionary

I have a configuration file, for example:

<ConfigurationFile> <Config name="some.configuration.setting" value="some.configuration.value"/> <Config name="some.configuration.setting2" value="some.configuration.value2"/> ... </ConfigurationFile> 

I am trying to read this in XML and convert it to a dictionary. I tried to code something this, but this is clearly wrong, as it does 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 someone can tell me how to do this, it will be very helpful. I could always, of course, read it

+4
source share
3 answers

To give a more detailed answer - you can use ToDictionary in the same way as written in your question. In the missing part, you need to specify a “key selector” and “value selector”, these are two functions that tell the ToDictionary method that the part of the object you are converting is the key and the value. You have already extracted these two into an anonymous type so you 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 that I removed the specification of the parameters of the generic type. The C # compiler shows this automatically (and we use overload with three generic arguments ). However, you can avoid using an anonymous type - in the above version, you simply create it to store the value temporarily. The simplest version would be simple:

 var configDictionary = xmlDocument.Descendants("Config").ToDictionary( datum => datum.Attribute("name").Value, datum => datum.Attribute("value").Value ); 
+14
source

Your ToDictionary call requires a choice of key and value. Starting from what you have, it could be

 var dictionary = yourQuery.ToDictionary(item => item.Name, item => item.Value); 
0
source

There is no need to have a query as you are just doing a projection. Move the projection into a call to ToDictionary() :

 var configDictionary = xmlDocument.Descendants("Config") .ToDictionary(e => e.Attribute("name").Value, e => e.Attribute("value").Value); 
0
source

Source: https://habr.com/ru/post/1337078/


All Articles