【问题标题】:How to Create Dictionary<int, string> via LINQ to XML?如何通过 LINQ to XML 创建 Dictionary<int, string>?
【发布时间】:2010-05-14 00:27:12
【问题描述】:

我有以下 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>

我有以下代码,我将在其中获取 Dictionary&lt;int, string&gt;() 对象

myObject.FootNotes 

这样每一行都是一个键/值对

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")
                       )
                  )
  };

我不确定如何将它从 XML 中获取到对象中。任何人都可以提出解决方案吗?

【问题讨论】:

    标签: c# dictionary linq-to-xml


    【解决方案1】:

    您的代码几乎是正确的。试试这个细微的变化:

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

    我不认为长 from ... select 语法在这里真的有很大帮助。我会改用这个稍微简单的代码:

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

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

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

    【讨论】:

    • 代码几乎正确,除了(from fn in 和结尾的)。您在编辑之前提供的示例指出了这一点。您应该恢复上次编辑,以便我可以选择此作为正确答案
    • @DaveDev:实际上我现在也添加了 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    相关资源
    最近更新 更多