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'
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.
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.
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.
var dictionary = db .Table .Select(p => new { p.Key, p.Value }) .AsEnumerable() .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) ;
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With