我想为Where子句
构建一个表达式Expression<Func<T, bool>>
对接受
类型参数的方法Expression<Func<T, DateTime>>
我想操纵我的DateTime属性来比较其内部属性,比如将比较子句添加到日,月和年属性。
我的方法如下:
public static class MyUtils
{
public static Expression<Func<T, bool>> GetTime<T>(this Expression<Func<T, bool>> pExp, Expression<Func<T, DateTime>> MyProperty, int day, int month, int year)
{
}
}
我想像这样使用它:
Expression<Func<MyClass, bool>> vExpression = p => false;
vExpression = vExpression.GetTime<MyClass>(c => c.MyDate, 21, 12, 2012);
因此,在方法结束时,我对“MyDate”属性和各个日期值进行了一些比较。
可以这样做吗?
答案 0 :(得分:2)
也许是这样的:
static Expression<Func<T, bool>> GetTime<T>(
Expression<Func<T, DateTime>> expression,
DateTime compare
)
{
var comparison = Expression.Equal(expression.Body, Expression.Constant(compare));
return Expression.Lambda<Func<T, bool>>(comparison, expression.Parameters);
}
然后你可以这样做:
Expression<Func<MyClass, bool>> vExpression = GetTime<MyClass>(
c => c.MyDate,
new DateTime(2012, 12, 21)
);
修改强>
上面的代码显示了如何基于旧表达式树创建新的表达式树。您可以使用任何允许的构造创建新的表达式树。这是一个稍微复杂的例子:
static Expression<Func<T, bool>> GetTime<T>(
Expression<Func<T, DateTime>> expression,
DateTime compare
)
{
var comparison = Expression.AndAlso(
Expression.AndAlso(
Expression.GreaterThanOrEqual(
Expression.Property(expression.Body, "Year"),
Expression.Constant(compare.Year)
),
Expression.GreaterThanOrEqual(
Expression.Property(expression.Body, "Month"),
Expression.Constant(compare.Month)
)
),
Expression.GreaterThanOrEqual(
Expression.Property(expression.Body, "Day"),
Expression.Constant(compare.Day)
)
);
return Expression.Lambda<Func<T, bool>>(comparison, expression.Parameters);
}