Search code examples
c#.netlambdaexpression-trees

Expression.Call in simple lambda expression. Is it possible?


I need to generate a lambda expression like

item => item.Id > 5 && item.Name.StartsWith("Dish")

Ok, item.Id > 5 is simple

var item = Expression.Parameter(typeof(Item), "item");

var propId = Expression.Property(item,"Id");
var valueId = Expression.Constant(5);
var idMoreThanFive = Expression.GreaterThan(propId, valueId);

But the second part is more complex for me...

var propName = Expression.Property(item,"Name");
var valueName = Expression.Constant("Dish");

How to call StartsWith for propName?


Solution

  • You'll have to get a MethodInfo representing the string.StartsWith(string) method and then use Expression.Call to construct the expression representing the instancemethod call:

    var property = Expression.Property(item, "Name");
    var method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
    var argument = Expression.Constant("Dish");
    
    // item.Name.StartsWith("Dish")
    var startsWithDishExpr = Expression.Call(property, method, argument);
    

    You'll then have to && the subexpressions together to create the body.

    var lambdaBody = Expression.AndAlso(idMoreThanFive, startsWithDishExpr);
    

    And then finally construct the lambda:

    var lambda = Expression.Lambda<Func<Item, bool>>(lambdaBody, item);