Linq ToDictionary not defined?

I have this code

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) 

I do not know what is wrong with this code.

The msg compile-time error says: System.Generic.IEnumerable does not contain a definition and the best method overload method has some invalid arguments. I see only two ToDictionary method overloads in my visual studio, for example, documentation, while I came across more than two ToDictionary overloads on the Internet
Edit Here is the exact error message at compile time

Error 13 ' System.Collections.Generic.IEnumerable<AnonymousType#1> ' does not contain a definition for ' ToDictionary ' and the best extension is the overload of the System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>, System.Collections.Generic.IEqualityComparer<TKey>) 'has some invalid arguments

+4
source share
3 answers

The compiler message fixes the error: there is no ToDictionary method that can accept the specified arguments and types.

The error here is in defining type arguments on ToDictionary . The MSDN documentation defines the extension method as ToDictionary<TKey, TSource> . The source in your example is IEnumerable<AnonymousType#1> , but you specified a List<string> .

To correct the error, omit type arguments; the compiler will output the correct types. You can optionally combine the conversion of Select and ToDictionary into one statement:

 var contacts = dr.mktDoctorContacts .GroupBy(x => x.ContactType) .ToDictionary( y => y.Key, y => y.Select(x => x.Contact).ToList()); 
+7
source

Do not run this group operation in the database, this will lead to the fact that the elements of each group will be selected in separate rounds.

 ILookup<string, string> contacts = dr.mktDoctorContacts .ToLookup<Contact, string, string>(x => x.ContactType, x => x.Contact); 
+1
source

Rewrote your code (and added .AsEnumerable() ):

 var dictionary = dr.mktDoctorContacts .GroupBy(x => x.ContactType) .AsEnumerable() .ToDictionary( i => i.Key, i => i.Select(x => x.Contact).ToList() ) ); 
0
source

Source: https://habr.com/ru/post/1341129/


All Articles