C# 将列表转换为字典

Mar*_*rth 0 c# lambda todictionary

我正在尝试将 a 转换List<Ctrl>为 a Dictionary<string, Ctrl>usingCtrl.Name作为键。我已经参考了这个页面来尝试实现这一点: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);
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息ToDictionary<string, Ctrl>(a => a, b => b.Name)实例参数:无法从“System.Collections.Generic.List<AppData.Ctrl>”转换为“System.Collections.Generic.IEnumerable”

参数 3:无法从“lambda 表达式”转换为“System.Collections.Generic.IEqualityComparer<AppData.Ctrl>”

参数 2:无法从“lambda 表达式”转换为“System.Func<string,AppData.Ctrl>”

'System.Collections.Generic.List<AppData.Ctrl>' 不包含 'ToDictionary' 的定义和最佳扩展方法重载 'System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable , System.Func<TSource,TKey>, System.Collections.Generic.IEqualityComparer)' 有一些无效的参数

不完全确定我在这里做错了什么。此外,对我来说,字典是按顺序声明的<key, value>,而 ToDictionary 构造函数按顺序采用 lambda 函数,这对我来说似乎很奇怪<value, key>

我该如何解决?我有点失落。谢谢。

编辑:添加到列表中,并包含所有编译时错误。

编辑 2:删除了 ToDictionary 的类型参数。我还删除了多余的 ToList() 调用,因此代码如下:

oActionControls = (from ctrl in _ctrls.Items
                   where ctrl.CtrlTypeCode == "BUTTON"
                   orderby ctrl.TabIndex
                   select ctrl).ToDictionary(a => a.Name);
Run Code Online (Sandbox Code Playgroud)

哪个工作正常。

kaf*_*opp 5

假设您有一个List<Ctrl>,您可以简单地通过.ToDictionary()使用键选择器参数调用来创建字典(请参阅MS 文档):

Dictionary<string, Ctrl> actionControls = ctrls.ToDictionary(ctrl => ctrl.Name);
Run Code Online (Sandbox Code Playgroud)

确保你有一个using System.Linq;声明。

此外 - 字典没有顺序,因此您可以order by从查询中删除该子句。

可验证的例子:

var ctrls = new List<Ctrl>
{
    new Ctrl { CtrlTypeCode = "1", Name = "My value 1" },
    new Ctrl { CtrlTypeCode = "2", Name = "My value 2" },
    new Ctrl { CtrlTypeCode = "3", Name = "My value 3" },
};
Dictionary<string, Ctrl> actionControls = ctrls.ToDictionary(ctrl => ctrl.Name);
Run Code Online (Sandbox Code Playgroud)