C# 通过 EF / Linq 投射到 KeyValuePair

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17301972/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:05:56  来源:igfitidea点击:

Projecting into KeyValuePair via EF / Linq

c#linqentity-frameworkprojectionkeyvaluepair

提问by GrandMasterFlush

I'm trying to load a list of KeyValuePairs from an EF / Linq query like this:

我正在尝试从 EF/Linq 查询中加载 KeyValuePairs 列表,如下所示:

return (from o in context.myTable 
select new KeyValuePair<int, string>(o.columnA, o.columnB)).ToList();

My problem is that this results in the error

我的问题是这会导致错误

"Only parameterless constructors and initializers are supported in LINQ to Entities."

“LINQ to Entities 中仅支持无参数构造函数和初始值设定项。”

Is there an easy way around this? I know I could create a custom class for this instead of using KeyValuePair but that does seem like re-inventing the wheel.

有没有简单的方法来解决这个问题?我知道我可以为此创建一个自定义类而不是使用 KeyValuePair 但这似乎是在重新发明轮子。

采纳答案by Sergey Berezovskiy

Select only columnA and columnB from your table, and move further processing in memory:

从表中仅选择 columnA 和 columnB,并在内存中进行进一步处理:

return context.myTable
              .Select(o => new { o.columnA, o.columnB }) // only two fields
              .AsEnumerable() // to clients memory
              .Select(o => new KeyValuePair<int, string>(o.columnA, o.columnB))
              .ToList();

Consider also to create dictionary which contains KeyValuePairs:

还考虑创建包含 KeyValuePairs 的字典:

return context.myTable.ToDictionary(o => o.columnA, o => o.columnB).ToList();

回答by cuongle

Since LINQ to Entities does not support KeyValuePair, you should turns to LINQ to Object by using AsEnumerablefirst:

由于 LINQ to Entities 不支持KeyValuePair,您应该AsEnumerable首先使用 LINQ to Object :

return context.myTable
              .AsEnumerable()
              .Select(new KeyValuePair<int, string>(o.columnA, o.columnB))
              .ToList();

回答by Bartosz

There is also alternative, when you want to store multiple values for one key exists something what is called Lookup.

还有另一种选择,当您想为一个键存储多个值时,存在称为Lookup 的东西。

Represents a collection of keys each mapped to one or more values.

代表一组键,每个键都映射到一个或多个值。

Here you have some official documentations.

这里有一些官方文档

More over lookupseems to be much faster than Dictionary < TKey, List < TValue > >.

更多的查找似乎比Dictionary < TKey, List < TValue >>快得多