IEnumerable <T> .ToLookup <TKey,TValue>

Dar*_*bio 2 c# linq lookup lambda

我试图使用以下代码IEnumerable<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);
Run Code Online (Sandbox Code Playgroud)

但编译器抱怨:

实例参数:无法从'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表达式做错了什么?

hor*_*rgh 5

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

var lookup = list.ToLookup(a => a.Key);
Run Code Online (Sandbox Code Playgroud)

因为它应该是:

var lookup = list.ToLookup<KeyValuePair<string, object>, string>(a => a.Key);
Run Code Online (Sandbox Code Playgroud)