A Simple Dynamic Lambda Expression Query
var result = _people.Where(person => person.FirstName
== "John").ToList();
// Create parameter expression
var parameterExpression =
Expression.Parameter(Type.GetType(
"ExpressionTreeTests.Person"), "person");
// Create expression constant
var constant = Expression.Constant("John");
//The expression constant has to be compared to some property.
//The code in the next snippet creates a property expression.
var property = Expression.Property(parameterExpression,
"FirstName");
//Next, you need to bring the expression constant and property together.
//In this case, you wish to test whether or not a property is equal to a string constant.
//The following code brings those two expressions together:
var expression = Expression.Equal(property, constant);
//The expression variable's string representation is:
//{(person.FirstName == "John")}
//Once an expression has been created, you can create a lambda expression.
//The next code snippet accomplishes that task:
var lambda = Expression.Lambda<Func<Person,
bool>>(expression, parameterExpression);
//In this case, the lambda represents a delegate function that accepts a Person argument and returns a Boolean value to indicate whether the specified Person object meets the query criteria.
//In this case, the query criterion is whether the FirstName == "John".
//The following illustrates the string representation of the dynamic lambda expression:
//{person => (person.FirstName == "John")}
//This is identical to the lambda expression in the simple lambda expression query listed above.
//The only difference is that instead of embedding the definition in the code, you've built it dynamically.
//The last step before using the dynamic lambda expression is to compile it:
var compiledLambda = lambda.Compile();
//Now that the lambda is compiled, you can use it in a query:
var result = _people.Where(compiledLambda).ToList();