3

我正在尝试使用以下代码将 anIEnumerable<KeyValuePair<string, object>>转换为:ILookup<string, object>

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 表达式做错了什么?

4

1 回答 1

6

只需删除<string, object>要自动推断的类型:

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

因为它真的应该是:

var lookup = list.ToLookup<KeyValuePair<string, object>, string>(a => a.Key);
于 2012-11-28T04:19:07.330 回答