capypad
0 day streak
csharp / expert
Snippet

Dynamic Query Compilation via Expression Trees

Expression trees represent code in a tree-like data structure, where each node is an expression. Expert developers use this for metaprogramming, such as building dynamic LINQ providers or compiling highly optimized logic at runtime that would otherwise require slow reflection.

snippet.csharp
csharp
1
2
3
4
5
6
ParameterExpression param = Expression.Parameter(typeof(int), "x");
BinaryExpression body = Expression.GreaterThan(param, Expression.Constant(10));
Expression<Func<int, bool>> lambda = Expression.Lambda<Func<int, bool>>(body, param);
 
Func<int, bool> compiled = lambda.Compile();
bool result = compiled(15);
Breakdown
1
Expression.Lambda<Func<int, bool>>(body, param);
Defines the signature and logic of the anonymous function.
2
lambda.Compile();
Triggers the JIT compiler to turn the expression tree into executable IL code.