SelectMany()无法推断类型参数 – 为什么不呢?
我有一个Employee
表和一个Office
表。 它们通过EmployeeOffices
表以多对多关系连接EmployeeOffices
。
我想获得一个特定员工( CurrentEmployee
)与之关联的所有办公室的列表。
我以为我可以这样做:
foreach (var office in CurrentEmployee.EmployeeOffices.SelectMany(eo => eo.Office)) ;
但这给了我错误:
无法从用法中推断出方法’System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable,System.Func>)’的类型参数。 尝试显式指定类型参数。
我知道我可以添加类型参数。 但Intellisense认识到eo.Office
属于Office类型。 那么编译器为什么不清楚呢?
您传递给SelectMany
的委托返回的类型必须是IEnumerable
,但显然Office
不实现该接口。 看起来你只是简单地将SelectMany
与Select
方法混淆了。
-
SelectMany
用于将多个集合展平为新集合。 -
Select
用于将源集中的每个元素一对一映射到新集。
我想这就是你想要的:
foreach (var office in CurrentEmployee.EmployeeOffices.Select(eo => eo.Office))