Linq Expression

Tram Ho

We already know that lambda expressions can be assigned to Func or Action types to handle in collection memory. The .NET compiler converts an expression assigned to Func or Action into executable code at compile time. Linq introduces a new type called Expression that represents a strong lambda expression. It means that lambda expressions can also be assigned to the Expression type <TDelegate>. The .NET compiler converts the lambda expression assigned to the Expression <TDelegate> expression into an Expression expression tree instead of the executable code. This expression tree is used to Linq remotely query the data structure, build a runtime query from it (such as Linq-to-Sql, entity framework or any other Linq query that has an interface. is IQueryable <T>. The illustration below illustrates the difference when lambda expressions are assigned to Func or Action and Expression delegations in Linq.

Define an Expression

We declare a System.Linq.Expressions namespace and use an Expression <TDelegate> class to define an Expression. The requested Expression <TDelegate> is a Func or Action proxy. For example, you can assign a lambda expression to a variable isTenAger with the type Func delegate as follows:

Now we convert the above expression of Func into Expression by wrapping Func with Expresstion as follows:

Expression<Func<Student, bool>> isTeenAgerExpr = s => s.age > 12 && s.age < 20;

In the same way, you can also package an Action <t> with an Expression if it has no return value.

Expression<Action<Student>> printStudentName = s => Console.WriteLine(s.StudentName);

Call an Expression

You can call a delegate encapsulated in an Expression the same way you call a proxy, but you must first translate it using the Compile () method. Compile () returns a Func or Action proxy that you can call it as a proxy.

Expression tree

The Expression tree, as the name implies, is nothing but its data structure arranged like a tree. Each node in the expression tree is an expression. For example, an expression tree is used to represent a mathematical expression x, y where x and y will be represented as an expression and arranged in a tree structure. The expression tree is a memory representation of the lambda expression. It contains elements of a query fact, not a result of a query. Tree expression makes the structure of lambda more explicit and clear. We can interact with the data in the expression tree just like any other data. For example, consider the following isTeenAgerExpr function:

Expression<Func<Student, bool>> isTeenAgerExpr = s => s.age > 12 && s.age < 20;

The compiler converts the above expression into the following:

We can also build an expression tree by hand, considering the following simple lambda example:

Func<Student, bool> isAdult = s => s.age >= 18;

This delegation is built by hand as follows:

Let’s look at an example of an Expression tree through the following code:


Share the news now

Source : Viblo