views:

368

answers:

2

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

+2  A: 

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.

Marc Gravell
Aaahh! so obvious now. Appreciated.
Kev
Is the AsEnumerable() needed?
Svish
@Svish: seems not.
Kev
A: 

Thanks! This helped me as well. The .AsEnumerable is what I was missing.

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