using System.Linq.Expressions; // create addition expression Expression addExpr = Expression.Add( Expression.Constant(1), Expression.Constant(2) ); // compile expression to a delegate FuncaddFunc = Expression.Lambda >(addExpr).Compile(); // invoke compiled expression int result = addFunc(); Console.WriteLine(result); // output: 3
using System.Linq.Expressions; // sample data ListIn this example, we create a dynamic filter expression using `Expression.OrElse()` method, which takes two input expressions (in the form of `EqualExpression`), and returns a new `BinaryExpression` representing the OR operation. We then compile the expression to a lambda function using `Expression.Lambdanames = new List { "Alice", "Bob", "Carol", "Dave" }; // create filter expression ParameterExpression param = Expression.Parameter(typeof(string), "name"); Expression > filterExpr = Expression.Lambda >( Expression.OrElse( Expression.Equal(param, Expression.Constant("Alice")), Expression.Equal(param, Expression.Constant("Bob")) ), param ); // apply filter expression to data var filteredNames = names.AsQueryable().Where(filterExpr); foreach (var name in filteredNames) { Console.WriteLine(name); // output: Alice, Bob }