如何计算谓词表达式

时间:2014-08-01 05:27:16

标签: c# .net

我有一个GenericEntity,下面是代码

private Expression<Func<GenericEntity, bool>>GetGenericEntitySearchExpression(GenericEntityParameter searchParameter)
{
   var predicate = PredicateBuilder.True<GenericEntity>();
   if (searchParameter.RegionCode == 1)
   {
       predicate = predicate.And<GenericEntity>(e => e.RegionCode == searchParameter.RegionCode);
   }

   if (searchParameter.CountryCode > 0)
   {
        predicate = predicate.And<GenericEntity>(e => e.CountryCode == searchParameter.CountryCode);
   }
}

GetGenericEntitySearchExpression()返回表达式。有没有办法知道有多少表达式被添加,你可以从代码中看到它取决于它将附加条件的条件

2 个答案:

答案 0 :(得分:1)

您可以创建表达式访问者来计算与谓词匹配的表达式的数量:

public class Counter : ExpressionVisitor
{
    private Func<Expression, bool> predicate;
    public int Count { get; private set; }
    public Counter(Func<Expression, bool> predicate)
    {
        this.predicate = predicate;
    }
    public override Expression Visit(Expression node)
    {
        if (predicate(node))
            Count++;
        return base.Visit(node);
    }
}

public static int Count(
    this Expression expression, 
    Func<Expression, bool> predicate)
{
    var counter = new Counter(predicate);
    counter.Visit(expression);
    return counter.Count;
}

然后只计算And个表达式的数量。

var numberOfAnds = expression.Count(ex => ex.NodeType == ExpressionType.AndAlso);

答案 1 :(得分:-1)

感谢@servy的提示。我使用Generic类而不是继承。可能有比下面提到的代码更好的方法

private ExpressionWithCounter<GenericEntity> GetGenericEntitySearchExpression(GenericEntityParameter searchParameter)
{
    var expressionCounter = new ExpressionWithCounter<GenericEntity>();
    expressionCounter.Predicate = PredicateBuilder.True<GenericEntity>();

    if (searchParameter.RegionCode == 1)
    {
    expressionCounter.Append(expressionCounter.Predicate.And<GenericEntity>(e => e.RegionCode == searchParameter.RegionCode));
    }

    if (searchParameter.CountryCode > 0)
    {
        expressionCounter.Append(expressionCounter.Predicate.And<GenericEntity>(e => e.CountryCode == searchParameter.CountryCode));
    }
}


public class ExpressionWithCounter<T>
{
    public Expression<Func<T, bool>> Predicate;
    public int Count { get; private set; }

    public void Append(Expression<Func<T, bool>> expression)
    {
        Predicate = expression;
        Count++;
    }
}


ExpressionWithCounter<GenericEntity> whereExperssion = GetGenericEntitySearchExpression(searchParameter);

//Is Any expression added?
if(whereExperssion.Count > 0)
{
    //Perform any action
}