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?
You’ll have to get a
MethodInforepresenting thestring.StartsWith(string)method and then useExpression.Callto construct the expression representing the instancemethod call:You’ll then have to
&&the subexpressions together to create the body.And then finally construct the lambda: