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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:42:19  来源:igfitidea点击:

SelectMany() Cannot Infer Type Argument -- Why Not?

c#entity-frameworklinq

提问by Jonathan Wood

I have an Employeetable and an Officetable. These are joined in a many-to-many relationship via the EmployeeOfficestable.

我有一张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.Officeis 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 SelectManymust be an IEnumerable<TResult>, but evidently, Officedoesn't implement that interface. It looks like you've simply confused SelectManyfor the simple Selectmethod.

您传递给的委托返回的类型SelectMany必须是 an IEnumerable<TResult>,但显然Office没有实现该接口。看起来您只是SelectMany对简单的Select方法感到困惑。

  • SelectManyis for flattening multiple sets into a new set.
  • Selectis 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))