IEnumerable<T>.ToLookup<TKey, TValue>

3

我想把一个 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);

但编译器报错:
实例参数:无法从 'System.Collections.Generic.List>' 转换为 'System.Collections.Generic.IEnumerable'
还有
'System.Collections.Generic.List>' 不包含 'ToLookup' 的定义,最佳的扩展方法重载 'System.Linq.Enumerable.ToLookup(System.Collections.Generic.IEnumerable,System.Func)' 存在一些无效参数
以及
无法将 'lambda expression' 转换为 'System.Func'
我的 lambda 表达式哪里出了问题呢?
1个回答

6

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

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

如实应该是的:
var lookup = list.ToLookup<KeyValuePair<string, object>, string>(a => a.Key);

啊哈!谢谢,我没有从文档中意识到第一个参数是“源”类型。 - Darbio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接