text
stringlengths
0
13.4k
var predicate = PredicateExtensions.BuildEqualPredicate<Entity>(
_ => _.Field,
"VALUE");
var results = context.Entity.Where(predicate).ToList();
Section 11.2: Simple Expression Tree Generated by the C#
Compiler
Consider the following C# code
Expression<Func<int, int>> expression = a => a + 1;
Because the C# compiler sees that the lambda expression is assigned to an Expression type rather than a delegate
type it generates an expression tree roughly equivalent to this code
ParameterExpression parameterA = Expression.Parameter(typeof(int), "a");
var expression = (Expression<Func<int, int>>)Expression.Lambda(
Expression.Add(
parameterA,
Expression.Constant(1)),
parameterA);
The root of the tree is the lambda expression which contains a body and a list of parameters. The lambda has 1
parameter called "a". The body is a single expression of CLR type BinaryExpression and NodeType of Add. This
expression represents addition. It has two subexpressions denoted as Left and Right. Left is the
GoalKicker.com – .NET Framework Notes for Professionals
50
ParameterExpression for the parameter "a" and Right is a ConstantExpression with the value 1.
The simplest usage of this expression is printing it:
Console.WriteLine(expression); //prints a => (a + 1)
Which prints the equivalent C# code.
The expression tree can be compiled into a C# delegate and executed by the CLR
Func<int, int> lambda = expression.Compile();
Console.WriteLine(lambda(2)); //prints 3
Usually expressions are translated to other languages like SQL, but can be also used to invoke private, protected
and internal members of public or non-public types as alternative to Reflection.
Section 11.3: Expression for retrieving a static field
Having example type like this:
public TestClass
{
public static string StaticPublicField = "StaticPublicFieldValue";
}
We can retrieve value of StaticPublicField:
var fieldExpr = Expression.Field(null, typeof(TestClass), "StaticPublicField");
var labmda = Expression.Lambda<Func<string>>(fieldExpr);
It can be then i.e. compiled into a delegate for retrieving field value.
Func<string> retriever = lambda.Compile();
var fieldValue = retriever();
//fieldValue result is StaticPublicFieldValue
Section 11.4: InvocationExpression Class
InvocationExpression class allows invocation of other lambda expressions that are parts of the same Expression
tree.
You create them with static Expression.Invoke method.
Problem We want to get on the items which have "car" in their description. We need to check it for null before
searching for a string inside but we don't want it to be called excessively, as the computation could be expensive.
using System;
using System.Linq;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
var elements = new[] {
GoalKicker.com – .NET Framework Notes for Professionals
51
new Element { Description = "car" },
new Element { Description = "cargo" },