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?
Which is NOT true about lambda statements? A statement lambda cannot return a value.
Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
The => token is supported in two forms: as the lambda operator and as a separator of a member name and the member implementation in an expression body definition.
A lambda expression is a function or subroutine without a name that can be used wherever a delegate is valid. Lambda expressions can be functions or subroutines and can be single-line or multi-line. You can pass values from the current scope to a lambda expression. The RemoveHandler statement is an exception.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With