Linq-to-SQL ToDictionary()
C#LinqLinq to-SqlC# Problem Overview
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
C# Solutions
Solution 1 - C#
var dictionary = db
.Table
.Select(p => new { p.Key, p.Value })
.AsEnumerable()
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
;
Solution 2 - C#
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);
Solution 3 - C#
Thanks guys, your answers helped me fix this, should be:
var dic = db
.Table
.Select(p => new { p.Key, p.Value })
.AsEnumerable()
.ToDictionary(k=> k.Key, v => v.Value);
Solution 4 - C#
Why would you create an anonymous object for every item in the table just to convert it?
You could simply use something like:
IDictionary<string, string> dic = db.Table.ToDictionary(row => row.Key, row => row.Value);
You may need to include an AsEnumerable() call between Table and ToDictionary().
I don't know the exact type of db.Table.
Also correct the first sample, your second loop variable is mismatching at declaration and usage.