Monday, April 25, 2011

Why does ToDictionary<K,V>() generate a compiler error when used with LINQ to SQL?

Hi All,

Following on from this question:

Linq-to-SQL ToDictionary()

I have a table called Domains, it has two columns:

DomainID int
DomainName varchar(250)

I want to return a Dictionary<int, string>. When I try either of the following LINQ to SQL code:

Dictionary<int, string> dict =
    dbc
    .Domains
    .Select(d => new {d.DomainID, d.DomainName})
    .AsEnumerable()
    .ToDictionary<int, string>(k => k.DomainID, k => k.DomainName);

or

Dictionary<int, string> dict = 
    (from d in dbc.Domains
      select new { d.DomainID, d.DomainName })
      .AsEnumerable()
      .ToDictionary<int, string>(k => k.DomainID, k => k.DomainName);

I get the following compile error:

Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<int>'

The scenario here seems the same as q245168 and should work, am I missing something obvious?

Cheers
Kev

From stackoverflow
  • Try removing the generic type arguments; the first is the source, not the key:

    Dictionary<int, string> dict = 
    (from d in dbc.Domains
      select new { d.DomainID, d.DomainName })
      .AsEnumerable()
      .ToDictionary(k => k.DomainID, k => k.DomainName); // <==== no angles
    

    Here, we are using generic type inference to supply the details.

    Kev : Aaahh! so obvious now. Appreciated.
    Svish : Is the AsEnumerable() needed?
    Kev : @Svish: seems not.
  • Thanks! This helped me as well. The .AsEnumerable is what I was missing.

    Lasse V. Karlsen : Please leave comments instead of answers, this is not a discussion board.

0 comments:

Post a Comment