Search code examples
c#recursionlambdaexpressionexpression-trees

Creating an (Lambda) Expression using recursion


I have the following dictionary:

Dictionary<string, PropertyInfo> filterProperties;

The content of this dictionary can be like this:

- "Language": [QueryData.Lang],
- "Id": [Querydata.UserId]

Each string key maps to a property of a my QueryData type.

Now let's suppose I have the following QueryData instance:

QueryData: { Lang= "en", UserId = "mcicero" }

Using the previous dictionary as example, I want to build the following expression:

e => e.Language == "en" && e.Id == "mcicero";

As you can see the dictionary keys are used for accesing the properties of e, and the dictionary values (QueryData properties) are used for specifying constants in the binary equal expressions.

e is of type Entity, and is guaranteed to have this properties.

The resulting expression should be of type Expression<Func<Entity, bool>>

How can I build this expression using recursion?

I say recursion because it sounds like a natural solution, but an iterative one would be preferred.

I tried the iterative alternative and ended up with an ugly and not so understandable code.

However, I am having trouble creating a recursion method for this problem.


Solution

  • Leaving the creation of the individual expression to you, simply combine them together in an iterative loop:

    // For an IEnumerable<Expression> in "expressions"
    Expression left = null;
    foreach(var right in expressions)
    {
      if(left == null)
        left = right;
      else
        left = Expression.And(left, right);
    }
    // Combined expression is in "left"
    // Don't forget it will be null if there were no expressions provided...
    

    Or in one line with LINQ:

    var expr = expressions.Aggregate(Expression.And);