Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 611
Codewerks Avatar asked Oct 28 '08 22:10

Codewerks


People also ask

How does a LINQ query transform to a SQL query?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.

What is ToDictionary in LINQ C#?

In LINQ, ToDictionary() Method is used to convert the items of list/collection(IEnumerable<T>) to new dictionary object (Dictionary<TKey,TValue>) and it will optimize the list/collection items by required values only.

What does .include do in LINQ?

Introduction to LINQ Include. LINQ include helps out to include the related entities which loaded from the database. It allows retrieving the similar entities to be read from database in a same query. LINQ Include() which point towards similar entities must read from the database to get in a single query.


2 Answers

var dictionary = db     .Table     .Select(p => new { p.Key, p.Value })     .AsEnumerable()     .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) ; 
like image 166
yfeldblum Avatar answered Sep 24 '22 17:09

yfeldblum


You are only defining the key, but you need to include the value also:

var dic = (from p in db.Table              select new {p.Key, p.Value })             .ToDictionary(p => p.Key, p=> p.Value); 
like image 43
Christian C. Salvadó Avatar answered Sep 21 '22 17:09

Christian C. Salvadó