SelectMany()不能引用类型参数 - 为什么不? [英] SelectMany() Cannot Infer Type Argument -- Why Not?

查看:81
本文介绍了SelectMany()不能引用类型参数 - 为什么不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Employee 表和一个 Office 表。这些通过 EmployeeOffices 表加入到多对多关系。



我想要得到一个特定员工( CurrentEmployee )关联的所有办公室的列表。



我以为我可以做某事如下所示:

  foreach(Current Office中的办公室(Eo =&e; eo.Office))
;

但是这给了我错误:


方法'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable,System.Func>)'的类型参数不能从使用推断出来。尝试明确指定类型参数。


我明白我可以添加类型参数。但Intellisense认为 eo.Office 是Office类型。那么为什么编译器不清楚呢?

解决方案

你所转发的代理返回给 SelectMany 必须是 IEnumerable< TResult> ,但显然, Office 不实现该接口。对于简单的选择方法,您似乎已经简单地困惑了 SelectMany




  • SelectMany 用于将多个集合变成新集合。

  • 选择 是一对一的,将一个源中的每个元素映射到一个新集合。



我认为这是你想要的:

  foreach(Current Office中的var office).EmployeeOffices.Select(eo =&e; eo.Office))
/ pre>

I have an Employee table and an Office table. These are joined in a many-to-many relationship via the EmployeeOffices table.

I'd like to get a list of all the offices a particular employee (CurrentEmployee) is associated with.

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.

I understand I could add type arguments. But Intellisense recognizes that eo.Office is of type Office. So why isn't this clear to the compiler?

解决方案

The type returned by the delegate you pass to SelectMany must be an IEnumerable<TResult>, but evidently, Office doesn't implement that interface. It looks like you've simply confused SelectMany for the simple Select method.

  • SelectMany is for flattening multiple sets into a new set.
  • Select is for one-to-one mapping each element in a source set to a new set.

I think this is what you want:

foreach (var office in CurrentEmployee.EmployeeOffices.Select(eo => eo.Office))

这篇关于SelectMany()不能引用类型参数 - 为什么不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆