C# – Linq-to-SQL ToDictionary()


How do I properly convert two columns from SQL (2008) using Linq into a Dictionary (for caching)?

I currently loop through the IQueryable b/c I can't get the ToDictionary method to work. Any ideas?
This works:

var query = from p in db.Table
            select p;

Dictionary<string, string> dic = new Dictionary<string, string>();

foreach (var p in query)
    dic.Add(sub.Key, sub.Value);

What I'd really like to do is something like this, which doesn't seem to work:

var dic = (from p in db.Table
             select new {p.Key, p.Value })
            .ToDictionary<string, string>(p => p.Key);

But I get this error:
Cannot convert from 'System.Linq.IQueryable' to 'System.Collections.Generic.IEnumerable'

Best Solution

var dictionary = db
    .Select(p => new { p.Key, p.Value })
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)