Linq-to-SQL ToDictionary()

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)

  • -1错误是`<string,string>`部分使它使用`public static Dictionary <TKey,TSource> ToDictionary <TSource,TKey>(这个IEnumerable <TSource>源,Func <TSource,TKey> keySelector, IEqualityComparer <TKey> comparer);`重载而不是`public static Dictionary <TKey,TElement> ToDictionary <TSource,TKey,TElement>(这个IEnumerable <TSource>源,Func <TSource,TKey> keySelector,Func <TSource,TElement > elementSelector);`重载. (3认同)

Cod*_*rks 9

谢谢大家,你的答案帮助我解决了这个问题,应该是:

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)

  • 你需要AsEnumerable()的原因是因为LINQ to SQL不混合本地和远程(SQL)处理,所以这导致第一部分在SQL服务器上执行,然后最后一部分使用LINQ to Objects在本地执行做Dictionarys :) (5认同)