Linq-to-SQL ToDictionary()

如何使用 Linq 正确地将 SQL (2008)中的两列转换为 Dictionary(用于缓存) ?

我目前正在循环使用 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);
}

我真正想做的是这样的事情,似乎没有工作:

var dic = (from p in db.Table
select new {p.Key, p.Value })
.ToDictionary<string, string>(p => p.Key);

但我得到了这个错误:

无法从“ System.Linq.IQueryable < Anonymous ousType # 1 >”转换为 ‘ System. Collections. Generic.IEnumable’

75329 次浏览
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);

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);

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.