Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 543
CodeAddicted Avatar asked Nov 30 '11 05:11

CodeAddicted


People also ask

Which sentence about lambda statements is not true?

Which is NOT true about lambda statements? A statement lambda cannot return a value.

What is the type of a lambda expression?

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.

What is the use of => in C#?

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.

Which is a valid type of lambda function?

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.


1 Answers

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);
like image 60
Ani Avatar answered Oct 08 '22 05:10

Ani