How to Create Dictionary<int, string> via LINQ to XML?

℡╲_俬逩灬. 提交于 2019-12-12 15:41:37

问题


I have the following XML:

<FootNotes>
  <Line id="10306" reference="*"></Line>
  <Line id="10308" reference="**"></Line>
  <Line id="10309" reference="***"></Line>
  <Line id="10310" reference="****"></Line>
  <Line id="10311" reference="+"></Line>
</FootNotes>

and I have the following code where I'm to get a Dictionary<int, string>() object into

myObject.FootNotes 

so that each Line is a Key/Value pair

var doc = XElement.Parse(xmlString);

var myObject = new
  {
      FootNotes = (from fn in doc
                       .Elements("FootNotes")
                       .Elements("Line")
                       .ToDictionary
                       (
                       column => (int) column.Attribute("id"),
                       column => (string) column.Attribute("reference")
                       )
                  )
  };

I am unsure how to get this from the XML into the object though. Can anyone suggest a solution?


回答1:


Your code is nearly correct. Try this slight variation instead:

FootNotes = (from fn in doc.Elements("FootNotes")
                           .Elements("Line")
             select fn).ToDictionary(
                 column => (int)column.Attribute("id"),
                 column => (string)column.Attribute("reference")
             )

I don't think the long from ... select syntax really helps much here. I'd use this slightly simpler code instead:

Footnotes = doc.Descendants("Line").ToDictionary(
                e => (int)e.Attribute("id"),
                e => (string)e.Attribute("reference")
            )

However you are using an anonymous type in your example code. You need to use a concrete type if you are planning to return this object to the caller.

var myObject = new SomeConcreteType
    {
        Footnotes = ....
    };


来源:https://stackoverflow.com/questions/2828336/how-to-create-dictionaryint-string-via-linq-to-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!