如何创建字典< INT,串>通过LINQ到XML? [英] How to Create Dictionary<int, string> via LINQ to XML?

查看:161
本文介绍了如何创建字典< INT,串>通过LINQ到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>

和我有下面的代码,我得到一个词典<整型,字符串>()对象为

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



我不确定如何从XML进入对象这虽然。任何人都可以提出一个解决方案?

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

推荐答案

您的代码几乎是正确的。试试这个微小的变化,而不是:

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 = ....
    };

这篇关于如何创建字典&LT; INT,串&GT;通过LINQ到XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆