【问题标题】:IEnumerable<T>.ToLookup<TKey, TValue>IEnumerable<T>.ToLookup<TKey, TValue>
【发布时间】:2012-11-28 04:16:29
【问题描述】:

我正在尝试使用以下代码将 IEnumerable&lt;KeyValuePair&lt;string, object&gt;&gt; 转换为 ILookup&lt;string, object&gt;:

var list = new List<KeyValuePair<string, object>>()
{
    new KeyValuePair<string, object>("London", null),
    new KeyValuePair<string, object>("London", null),
    new KeyValuePair<string, object>("London", null),
    new KeyValuePair<string, object>("Sydney", null)
};

var lookup = list.ToLookup<string, object>(a => a.Key);

但是编译器抱怨:

实例参数:无法从 'System.Collections.Generic.List>' 到 'System.Collections.Generic.IEnumerable'

和

'System.Collections.Generic.List>' 不包含“ToLookup”的定义和最佳扩展 方法重载 'System.Linq.Enumerable.ToLookup(System.Collections.Generic.IEnumerable, System.Func)' 有一些无效参数

和

无法从“lambda 表达式”转换为“System.Func”

我对 lambda 表达式做错了什么?

【问题讨论】:

    标签: c# linq lambda lookup


    【解决方案1】:

    只需删除 &lt;string, object&gt; 即可自动推断类型:

    var lookup = list.ToLookup(a => a.Key);
    

    应该是这样的:

    var lookup = list.ToLookup<KeyValuePair<string, object>, string>(a => a.Key);
    

    【讨论】:

    • 啊哈!谢谢,我没有从文档中意识到第一个参数是 Source 类型
    猜你喜欢
    • 2011-01-16
    • 2013-04-08
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    相关资源
    最近更新 更多