我有一个Employee
表和一个Office
表。它们通过 EmployeeOffices
表加入多对多关系。
我想获取与特定员工 (CurrentEmployee
) 关联的所有办公室的列表。
我以为我可以做这样的事情:
foreach (var office in CurrentEmployee.EmployeeOffices.SelectMany(eo => eo.Office))
;
但这给了我错误:
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.
我知道我可以添加类型参数。但是 Intellisense 识别出 eo.Office
是 Office 类型。那么,为什么编译器不清楚这一点?
最佳答案
您传递给 SelectMany
的委托(delegate)返回的类型必须是 IEnumerable<TResult>
,但显然,Office
不实现该接口(interface)。看起来你只是混淆了 SelectMany
对于简单 Select
方法。
-
SelectMany
用于将多个集合展平为一个新集合。 -
Select
用于将源集中的每个元素一对一映射到新集。
我想这就是你想要的:
foreach (var office in CurrentEmployee.EmployeeOffices.Select(eo => eo.Office))
关于c# - SelectMany() 无法推断类型参数——为什么不呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18602923/