Linq表达式构建器,在除法条件下添加条件

时间:2011-09-30 14:57:35

标签: .net linq expression divide

作为更大表达式的一部分,我们有分歧案例。这很简单

protected override Expression BuildDivideExpression(Expression left, Expression right)
{           
    return Expression.Divide(left, right);
}

我想改变它,如果左边是0则返回0,如果是左边则返回!= 0 ..这样的东西:

protected override Expression BuildDivideExpression(Expression left, Expression right)
{
    return Expression.Condition(left != 0, Expression.Constant(0), Expression.Divide(left, right))
}

但我无法弄清楚当前显示为“left!= 0”的条件位

1 个答案:

答案 0 :(得分:1)

我认为你的意思是如果right等于零,你希望结果为零。所以你想像{/ 3>}一样使用Expression.Equal

protected override Expression BuildDivideExpression(Expression left, Expression right)
{
    return Expression.Condition(Expression.Equal(right, Expression.Constant(0)),
                                Expression.Constant(0), 
                                Expression.Divide(left, right))
}