gpt4 book ai didi

Linq where 关键字与 Where 扩展和表达式参数

转载 作者:行者123 更新时间:2023-12-04 15:16:12 25 4
gpt4 key购买 nike

根据使用的语法,将表达式传递给 Linq 查询的行为会有所不同,我想知道为什么会这样。

假设我有这个非常通用的功能

private IEnumerable<Company> 
GetCompanies(Expression<Func<Company, bool>> whereClause)

以下实现按预期工作
private IEnumerable<Company> 
GetCompanies(Expression<Func<Company, bool>> whereClause)
{
return (from c in _ctx.Companies.Where(whereClause) select c);
}

但是下一个实现不能编译
(委托(delegate) 'System.Func' 不接受 1 个参数)
private IEnumerable<Company> 
GetCompanies(Expression<Func<Company, bool>> whereClause)
{
return (from c in _ctx.Companies where whereClause select c);
}

显然我可以只使用第一种语法,但我只是想知道为什么编译器不将 where 关键字与 Where 扩展名相同?

谢谢,
托马斯

最佳答案

涉及 where 的查询表达式的语法子句是(简化完整语法)

from identifier in expression where boolean-expression select expression
whereClause不是 bool 表达式。要背诵这一点,你必须说
from c in _ctx.Companies where whereClause.Compile()(c) select c;

请注意,如果 whereClauseFunc<Company, bool>你可以逃脱
from c in _ctx.Companies where whereClause(c) select c;

注意
from x in e where f

由编译器机械翻译成
(from x in e).Where(x => f)

我机械地说是因为它执行此转换而不进行任何语义分析以检查方法调用的有效性等。在所有查询表达式都已转换为 LINQ 方法调用表达式之后,该阶段出现。

尤其,
from c in _ctx.Companies where whereClause select c

被翻译成
_ctx.Companies.Where(c => whereClause).Select(c)

这显然是荒谬的。

原因是
from c in _ctx.Companies.Where(whereClause) select c

是合法的,因为 IEnumerable<Company>.Where有一个接受 Func<Company, bool> 的重载并且有来自 Expression<Func<Company, bool>> 的隐式转换到 Func<Company, bool> .

关于Linq where 关键字与 Where 扩展和表达式参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2372237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com