如何通过LINQ to XML创建Dictionary <int,string>?

Dav*_*Dev 3 c# dictionary linq-to-xml

我有以下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>
Run Code Online (Sandbox Code Playgroud)

我有以下代码,我要得到一个Dictionary<int, string>()对象

myObject.FootNotes 
Run Code Online (Sandbox Code Playgroud)

这样每条线都是一个键/值对

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")
                       )
                  )
  };
Run Code Online (Sandbox Code Playgroud)

我不确定如何将XML从XML转换为对象.谁有人建议解决方案?

Mar*_*ers 6

你的代码几乎是正确的.请尝试这种轻微变化:

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

我不认为长from ... select语法在这里真的有用.我会使用这个稍微简单的代码:

Footnotes = doc.Descendants("Line").ToDictionary(
                e => (int)e.Attribute("id"),
                e => (string)e.Attribute("reference")
            )
Run Code Online (Sandbox Code Playgroud)

但是,您在示例代码中使用匿名类型.如果计划将此对象返回给调用者,则需要使用具体类型.

var myObject = new SomeConcreteType
    {
        Footnotes = ....
    };
Run Code Online (Sandbox Code Playgroud)