C# 如何从表达式创建委托<;Func<&燃气轮机>;?(将参数传递给表达式)?
我有以下过滤器:C# 如何从表达式创建委托<;Func<&燃气轮机>;?(将参数传递给表达式)?,c#,linq,datetime,expression,C#,Linq,Datetime,Expression,我有以下过滤器: Expression<Func<Employee, bool>> fromDateFilterFourDays = z => EntityFunctions.TruncateTime(z.FiringDate) >= EntityFunctions.TruncateTime(DateTime.Now.AddDays(-4)); Expression<Func<Employee, bool>> fromDateFilt
Expression<Func<Employee, bool>> fromDateFilterFourDays = z => EntityFunctions.TruncateTime(z.FiringDate) >= EntityFunctions.TruncateTime(DateTime.Now.AddDays(-4));
Expression<Func<Employee, bool>> fromDateFilterSixDays = z => EntityFunctions.TruncateTime(z.FiringDate) >= EntityFunctions.TruncateTime(DateTime.Now.AddDays(-6));
Expression fromDateFilterFourDays=z=>EntityFunctions.TruncateTime(z.FiringDate)>=EntityFunctions.TruncateTime(DateTime.Now.AddDays(-4));
表达式fromDateFiltersXDays=z=>EntityFunctions.TruncateTime(z.FiringDate)>=EntityFunctions.TruncateTime(DateTime.Now.AddDays(-6));
如何使用此筛选器生成代理
我不想为每个给定的数字创建一个变量,即四天或六天 这是通过调用
Invoke()
方法完成的:
fromDateFilterFourDays.Invoke(employee);
或者您可以Compile()
将表达式编译为func,然后调用func:
var fromDateFilterFourDaysFunc = fromDateFilterFourDays.Compile();
fromDateFilterFourDaysFunc(employee);
通过使用
Compile
方法,您可以轻松地将Expression
转换为Func
但是,请记住,您提供的示例表达式不起作用,因为它们使用的只是用于映射相应数据库SQL函数的占位符,如果您尝试实际计算它们,则会引发异常(这将在Func
中发生)
从另一方面来说,如果问题实际上是如何参数化示例表达式,那么可能是这样的
static Expression<Func<Employee, bool>> DateFilter(int currentDateOffset)
{
return e => EntityFunctions.TruncateTime(e.FiringDate) >= DateTime.Today.AddDays(currentDateOffset);
}
静态表达式日期过滤器(int currentDateOffset)
{
返回e=>EntityFunctions.TruncateTime(e.FiringDate)>=DateTime.Today.AddDays(currentDateOffset);
}
我的理解是,您希望:
Expression<Func<Employee, int, bool>> fromDateFilter = (z, n) => EntityFunctions.TruncateTime(z.FiringDate) >= EntityFunctions.TruncateTime(DateTime.Now.AddDays(n));
对于复杂的linq表达式,我通常只创建一个帮助函数来简化表达式。在您的示例中,似乎要返回列表并传递一个指示日期范围的int参数。请注意,正如名称所示,
Compile
编译表达式。这是一个非常昂贵的操作,甚至相对于反射来说。不要经常这样做。
var del = fromDateFilter.Compile();
// use it
del(employee, -4);