C# Linq-to-SQL ToDictionary()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/245168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linq-to-SQL ToDictionary()
提问by Codewerks
How do I properly convert two columns from SQL (2008) using Linq into a Dictionary (for caching)?
如何使用 Linq 将 SQL (2008) 中的两列正确转换为字典(用于缓存)?
I currently loop through the IQueryable b/c I can't get the ToDictionary method to work. Any ideas? This works:
我目前通过 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);
}
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'
但我收到此错误:无法从“System.Linq.IQueryable”转换为“System.Collections.Generic.IEnumerable”
采纳答案by yfeldblum
var dictionary = db
.Table
.Select(p => new { p.Key, p.Value })
.AsEnumerable()
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
;
回答by CMS
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);
回答by Codewerks
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);
回答by TWiStErRob
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.
您可以简单地使用以下内容:
IDictionary<string, string> dic = db.Table.ToDictionary(row => row.Key, row => row.Value);
您可能需要在 Table 和 ToDictionary() 之间包含一个 AsEnumerable() 调用。我不知道 db.Table 的确切类型。
Also correct the first sample, your second loop variable is mismatching at declaration and usage.
还要更正第一个示例,您的第二个循环变量在声明和使用时不匹配。