Cod*_*rks 79 c# linq linq-to-sql
如何使用Linq将SQL(2008)中的两列正确转换为字典(用于缓存)?
我目前循环使用IQueryable b/c我无法使用ToDictionary方法.有任何想法吗?这有效:
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);
}
Run Code Online (Sandbox Code Playgroud)
我真正想做的是这样的事情,似乎不起作用:
var dic = (from p in db.Table
select new {p.Key, p.Value })
.ToDictionary<string, string>(p => p.Key);
Run Code Online (Sandbox Code Playgroud)
但我收到此错误:无法从'System.Linq.IQueryable'转换为'System.Collections.Generic.IEnumerable'
yfe*_*lum 118
var dictionary = db
.Table
.Select(p => new { p.Key, p.Value })
.AsEnumerable()
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
;
Run Code Online (Sandbox Code Playgroud)
CMS*_*CMS 16
您只是定义了键,但您还需要包含该值:
var dic = (from p in db.Table
select new {p.Key, p.Value })
.ToDictionary(p => p.Key, p=> p.Value);
Run Code Online (Sandbox Code Playgroud)
谢谢大家,你的答案帮助我解决了这个问题,应该是:
var dic = db
.Table
.Select(p => new { p.Key, p.Value })
.AsEnumerable()
.ToDictionary(k=> k.Key, v => v.Value);
Run Code Online (Sandbox Code Playgroud)