【发布时间】:2021-09-28 16:00:02
【问题描述】:
我正在尝试使用 Ctrl.Name 作为键将 List<Ctrl> 转换为 Dictionary<string, Ctrl>。我参考了这个页面来尝试实现这一点:Microsoft's Enumerable.ToDictionary Method page
因此,我的代码如下所示:
Dictionary<string, Ctrl> oActionControls;
oActionControls = (from ctrl in _ctrls.Items
where ctrl.CtrlTypeCode == "BUTTON"
orderby ctrl.TabIndex
select ctrl).ToList().ToDictionary<string, Ctrl>(a => a, b => b.Name);
我在ToDictionary<string, Ctrl>(a => a, b => b.Name) 上收到错误消息,内容如下:
实例参数:无法从 'System.Collections.Generic.List
参数 3:无法从“lambda 表达式”转换为“System.Collections.Generic.IEqualityComparer
参数 2:无法从 'lambda 表达式' 转换为 'System.Func
'System.Collections.Generic.List
不完全确定我在这里做错了什么。另外,对我来说,字典以<key, value> 的顺序声明,而 ToDictionary 构造函数以<value, key> 的顺序使用 lambda 函数,这对我来说似乎很奇怪。
我该如何解决这个问题?我有点失落。谢谢。
编辑: 添加到列表中,并包含所有编译时错误。
编辑 2: 删除了 ToDictionary 的类型参数。我还删除了多余的 ToList() 调用,因此代码如下:
oActionControls = (from ctrl in _ctrls.Items
where ctrl.CtrlTypeCode == "BUTTON"
orderby ctrl.TabIndex
select ctrl).ToDictionary(a => a.Name);
正常工作。
【问题讨论】:
-
您的代码中是否缺少
using System.Linq;? -
.ToDictionary<string, Ctrl>(b => b.Name, b => b);? -
不,
System.Linq在里面。错误出现在ToList().ToDictionary<string, Ctrl>(a => a, b => b.Name)而不是 Linq 语句上。 -
字典中的键是字符串,值是控件,但您的 ToDictionary 调用却相反。
-
哦,你也有错误的 lambda 表达式:
.ToDictionary(a => a.Name, b => b)(注意你不需要指定泛型类型,因为它们可以被推断出来。