Using LINQ to parse XML into Dictionary

前端 未结 3 1156
挽巷
挽巷 2021-01-06 03:35

I have a configuration file such as:


    
            


        
3条回答
  •  孤街浪徒
    2021-01-06 04:28

    To give a more detailed answer - you can use ToDictionary exactly as you wrote in your question. In the missing part, you need to specify "key selector" and "value selector" these are two functions that tell the ToDictionary method which part of the object that you're converting is a key and which is a value. You 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 generic type parameter specification. The C# compiler figures that automatically (and we're using an overload with three generic arguments). However, you can avoid using anonymous type - in the version above, you just create it to temporary store the value. The simplest version would be just:

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

提交回复
热议问题