score:2

Accepted answer

I'm not familiar with the System.Linq.Dynamic library, but assuming it produces normal, strongly typed Expression trees you can use an ExpressionVisitor.

This one counts the number of boolean logical operations like &&:

int CountConditions(Expression expr)
{
    var visitor = new CountBinaryOpsVisitor();
    visitor.Visit(expr);
    return visitor.BinaryOperationCount + 1;
}

class CountBinaryOpsVisitor : ExpressionVisitor
{
    public int BinaryOperationCount { get; private set; }

    protected override Expression VisitBinary(BinaryExpression node)
    {
        switch (node.NodeType)
        {
            case ExpressionType.And:
            case ExpressionType.AndAlso:
            case ExpressionType.Or:
            case ExpressionType.OrElse:
            case ExpressionType.ExclusiveOr:
                // Don't count bitwise integer operations, if they are even supported?
                if (node.Left.Type == typeof(bool))
                    BinaryOperationCount++;
                break;
        }
        return base.VisitBinary(node);
    }
}

An alternative approach would be to count the number of comparison operators (==, >= etc.), but I think that would need more complex code to handle boolean expressions like x.BooleanProp or x.Insurers.Any().

This implementation doesn't currently count conditional expressions (x ? y : z). Not sure how you would factor those into the number of conditions, especially when nested.


Related Articles