本文介绍了LINQ到SQL ToDictionary()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何正确使用LINQ转换两列从SQL(2008)成词典(缓存)?



我目前通过的IQueryable环路B / C我不能得到的ToDictionary方法来工作。有任何想法吗?
本作品:

  VAR的查询=从db.Table 
p器选择p;

&字典LT;字符串,字符串> DIC =新词典<字符串,字符串>();

的foreach(查询变种P)
{
dic.Add(sub.Key,sub.Value);
}



我真正想要做的是这样的事情,这没有按'不像是会工作:

 在db.Table 
VAR DIC =(上接第选择新的{p.Key, p.Value})
.ToDictionary<字符串,字符串>(p => p.Key);



不过,我得到这个错误:
不能从'System.Linq.IQueryable'转换为System.Collections.Generic.IEnumerable


解决方案

  VAR字典= DB 
。表
。选择(p =>新建{p.Key,p.Value})
.AsEnumerable()
.ToDictionary(KVP => kvp.Key,KVP = > kvp.Value)
;


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'

解决方案
var dictionary = db
    .Table
    .Select(p => new { p.Key, p.Value })
    .AsEnumerable()
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
;

这篇关于LINQ到SQL ToDictionary()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 06:13