c# - SelectMany() 无法推断类型参数——为什么不呢?

标签 c# entity-framework linq

我有一个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/

相关文章:

c# - 接口(interface)继承是一种不好的做法吗?

c# - child 继承 parent 长相

c# - 将字符串转换为字符串的泛型类型

java - boolean 字段 Oracle 与 MySQL

c# - 复制 IEnuemrable<T> - linq Select 未按预期运行

c# - 无法在 .NET Core 2.0 的启动构造函数中注入(inject)我自己的对象

c# - 实体对象附加/未附加到 dbContext

.net - 跨多个项目使用 EntityFramework

c# - 如何通过Linq从xml中获取值

c# - 为什么 PLINQ 比 for 循环慢?