简体   繁体   中英

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.

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);

For the interested ones, in one single line:

Expression expr = filterProperties.Select(i => Expression.Equal(
                                                  Expression.Property(entityParameter, i.Key),
                                                  Expression.Constant(i.Value.GetValue(queryObj))
                                         )).Aggregate(Expression.And);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM