【发布时间】: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