【问题标题】:XML to Dictionary using Linq To XML使用 Linq To XML 的 XML 到字典
【发布时间】:2015-08-18 16:53:52
【问题描述】:

好吧,我迷失在这个简单的事情上。 我想把这个xml转换成字典,基本上是这样的:

var xml = "<root><Hello>World</Hello><Foo>Bar</Foo></root>";
var doc = XDocument.Parse(xml);
var dic = new Dictionary<string, string>();
foreach (var elem in doc.Root.Elements())
{
    dic[elem.Name.LocalName] = elem.Value;
}

但我想用 ToDictionary,所以我写了这个:

var dic = doc.Root.Elements().ToDictionary<string, string>(e => e.Name.LocalName, e => e.Value);

但它不能编译!我收到这些错误

错误 1 ​​实例参数:无法从 'System.Collections.Generic.IEnumerable' 到 'System.Collections.Generic.IEnumerable' Program.cs 65 22
错误 2 'System.Collections.Generic.IEnumerable' 不包含“ToDictionary”的定义和最好的 扩展方法重载 'System.Linq.Enumerable.ToDictionary(System.Collections.Generic.IEnumerable, System.Func, System.Collections.Generic.IEqualityComparer)' 有一些无效 参数 Program.cs 65 22 错误 3 参数 2:无法从 'lambda 表达式' 到 'System.Func' Program.cs 65 71
错误 4 参数 3:无法从“lambda 表达式”转换为 'System.Collections.Generic.IEqualityComparer' Program.cs 65 94

【问题讨论】:

    标签: c# linq linq-to-xml


    【解决方案1】:

    这个

    var dic = doc.Root.Elements().ToDictionary<string, string>(e => e.Name.LocalName, e => e.Value);
    

    应该是这样的:

    var dic = doc.Root.Elements().ToDictionary(e => e.Name.LocalName, e => e.Value);
    

    您不必说明键的类型和值的类型。请查看here

    【讨论】:

    • 谢谢,我认为类型是可选的,我想我很困惑,因为你根本不写它们......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多