C# SelectMany() 无法推断类型参数——为什么不呢?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18602923/
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
SelectMany() Cannot Infer Type Argument -- Why Not?
提问by Jonathan Wood
I have an Employee
table and an Office
table. These are joined in a many-to-many relationship via the EmployeeOffices
table.
我有一张Employee
桌子和一张Office
桌子。这些通过EmployeeOffices
表连接成多对多关系。
I'd like to get a list of all the offices a particular employee (CurrentEmployee
) is associated with.
我想获取与特定员工 ( CurrentEmployee
) 关联的所有办公室的列表。
I thought I could do something like this:
我以为我可以做这样的事情:
foreach (var office in CurrentEmployee.EmployeeOffices.SelectMany(eo => eo.Office))
;
But this gives me the error:
但这给了我错误:
The type arguments for method 'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
无法从用法推断方法“System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>)”的类型参数。尝试明确指定类型参数。
I understand I could add type arguments. But Intellisense recognizes that eo.Office
is of type Office. So why isn't this clear to the compiler?
我知道我可以添加类型参数。但 Intellisense 识别出它eo.Office
属于 Office 类型。那么为什么编译器不清楚呢?
采纳答案by p.s.w.g
The type returned by the delegate you pass to SelectMany
must be an IEnumerable<TResult>
, but evidently, Office
doesn't implement that interface. It looks like you've simply confused SelectMany
for the simple Select
method.
您传递给的委托返回的类型SelectMany
必须是 an IEnumerable<TResult>
,但显然Office
没有实现该接口。看起来您只是SelectMany
对简单的Select
方法感到困惑。
SelectMany
is for flattening multiple sets into a new set.Select
is for one-to-one mapping each element in a source set to a new set.
SelectMany
用于将多个集合展平为一个新集合。Select
用于将源集中的每个元素一对一映射到新集合。
I think this is what you want:
我认为这就是你想要的:
foreach (var office in CurrentEmployee.EmployeeOffices.Select(eo => eo.Office))