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

Jon*_*ood 25 c# linq entity-framework

我有一张Employee桌子和一张Office桌子.这些通过EmployeeOffices表格以多对多的关系加入.

我想获得一个特定员工(CurrentEmployee)与之关联的所有办公室的列表.

我以为我可以这样做:

foreach (var office in CurrentEmployee.EmployeeOffices.SelectMany(eo => eo.Office))
    ;
Run Code Online (Sandbox Code Playgroud)

但这给了我错误:

用于方法"System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable,System.Func>)"类型参数不能从使用推断.尝试显式指定类型参数.

我知道我可以添加类型参数.但Intellisense认识到它eo.Office属于Office类型.那么为什么编译器不清楚这一点呢?

p.s*_*w.g 45

您传递给的委托返回的类型SelectMany必须是IEnumerable<TResult>,但显然Office不会实现该接口.看起来你只是简单地混淆SelectMany了简单的Select方法.

  • SelectMany 用于将多个集合展平为新集合.
  • Select 用于将源集中的每个元素一对一映射到新集.

我想这就是你想要的:

foreach (var office in CurrentEmployee.EmployeeOffices.Select(eo => eo.Office))
Run Code Online (Sandbox Code Playgroud)