Extension method returning lambda expression through compare

前端 未结 3 2001
情话喂你
情话喂你 2021-02-15 16:48

I\'m in the process of creating a more elaborate filtering system for this huge project of ours. One of the main predicates is being able to pass comparations through a string p

3条回答
  •  臣服心动
    2021-02-15 17:30

    One of the at-first-glance-magical features of the C# compiler can do the hard work for you. You probably know you can do this:

    Func totalCostIsUnder50 = d => d < 50m;
    

    that is, use a lambda expression to assign a Func. But did you know you can also do this:

    Expression> totalCostIsUnder50Expression = d => d < 50m;
    

    that is, use a lambda expression to assign an Expression that expresses a Func? It's pretty neat.

    Given you say

    The comparison builder is not the issue, that's the easy bit. The hard part is actually returning the expression

    I'm assuming you can fill in the blanks here; suppose we pass in `"<50" to:

    Expression> TotalCostCheckerBuilder(string criterion)
    {
        // Split criterion into operator and value
    
        // when operator is < do this:
        return d => d < value;
    
        // when operator is > do this:
        return d => d > value;
    
        // and so on
    }
    

    Finally, to compose your Expressions together with && (and still have an Expression), do this:

    var andExpression = Expression.And(firstExpression, secondExpression);
    

提交回复
热议问题