【问题标题】:SelectMany() Cannot Infer Type Argument -- Why Not?SelectMany() 无法推断类型参数——为什么不呢?
【发布时间】:2013-09-03 23:14:40
【问题描述】:

我有一个Employee 表和一个Office 表。它们通过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 类型。那么为什么编译器不清楚呢?

【问题讨论】:

    标签: c# entity-framework linq


    【解决方案1】:

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

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

    我想这就是你想要的:

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

    【讨论】:

    • 干!你说得对。 EmployeeOffices Office 关系是一对一的。我对整体上的多对多关系感到困惑。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 2023-03-15
    • 2014-02-04
    • 2019-02-11
    相关资源
    最近更新 更多