开发者

Linq expression builder, add conditional in divide case

开发者 https://www.devze.com 2023-04-10 07:41 出处:网络
As part of a larger set of expressions, we have our divide case.It\'s simple enough protected override Expression BuildDivideExpression(Expression left, Expression right)

As part of a larger set of expressions, we have our divide case. It's simple enough

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

I'd like to change it so that it returns 0 if left is 0, and as is if left != 0.. Something like this:

protected override Expression BuildDivideExpression(Expression left, Expression right)
{
    return Expression.Condition(left != 0, Expression.Constant(0), Expression.Divide(left, right))
}开发者_Go百科

But I can't figure out the conditional bit currently shown as "left != 0"

?


I think you mean if right is equal to zero you want the result to be zero. So you want to use Expression.Equal like so

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

精彩评论

暂无评论...
验证码 换一张
取 消