Linq ToDictionary未定义?

Muh*_*hid 9 linq linq-to-sql

我有这个代码

var contacts = dr.mktDoctorContacts
    .GroupBy(x => x.ContactType)
    .Select(zb => new 
     { 
         Key = zb.Key,
         GroupWiseContacts = zb.Select(x => x.Contact).ToList()
     })
    .ToDictionary<string,List<string>>(y => y.Key, y => y.GroupWiseContacts)
Run Code Online (Sandbox Code Playgroud)

我不知道这段代码有什么问题.

编译时错误msg说:System.Generic.IEnumerable不包含定义和最佳扩展方法重载有一些无效的参数.我在Visual Studio工具提示文档中只能看到ToDictionary方法的两个重载,而我在Web上遇到了两个以上的ToDictionary重载
编辑这里是编译时的确切错误消息

错误13' System.Collections.Generic.IEnumerable<AnonymousType#1>'不包含' '的定义,ToDictionary并且最佳扩展方法重载' System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>, System.Collections.Generic.IEqualityComparer<TKey>)'具有一些无效参数

Pau*_*ner 20

编译器消息使错误清楚:没有方法ToDictionary可以接受指定的参数和类型.

这里的错误在于指定类型参数ToDictionary.MSDN文档将扩展方法定义为ToDictionary<TKey, TSource>.您的示例中的源代码是IEnumerable<AnonymousType#1>,但您指定了一种类型List<string>.

要更正错误,请省略类型参数; 编译器将推断出正确的类型.您还可以将SelectToDictionary转换组合成一个语句:

var contacts = dr.mktDoctorContacts
    .GroupBy(x => x.ContactType)
    .ToDictionary(
        y => y.Key, 
        y => y.Select(x => x.Contact).ToList());
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢您指出这一点。我错误地认为它是 ToDictionary&lt;TKey, TElement&gt;。 (2认同)