Expression of Linq (common Expression types), linqexpression

Source: Internet
Author: User
Tags switch case try catch

Expression of Linq (common Expression types), linqexpression
Directory

Preface

Series of articles

Variable expression

Constant expression

Conditional expressions

Value assignment expression

Binary operator expression

Unary operator expression

Loop expression

Block expression

Summary

Preface

First, let's review the content of the previous article. The previous article introduces the parsing and compilation of the Expression Tree. If you forget it, you can review it at the entrance provided by the following series of articles. This article describes common expression types.

Common Expression types all have a common base class Expression. Create these types of objects by using APIs (that is, the Expression static method). First, introduce the namespace:

1 using System.Linq.Expressions;
Series of articles
A Preliminary Understanding of Linq's Lambda Expression

Linq's Lambda Advanced

Linq's implicit types, automatic properties, initializers, anonymous classes

Linq's extension method

See you at Linq Expression

Advanced Expression of Linq

Variable expression
Use ParameterExpression or ParameterExpression expression in the expression tree to represent the variable type. Let's look at an example. We define a variable i of type int:

  // ParameterExpression represents a named parameter expression.
 ParameterExpression i = Expression.Parameter (typeof (int), "i");
Or use

1 ParameterExpression j = Expression.Variable (typeof (int), "j");
Go to the definition through f12 and find that the comments of these two methods are almost the same. The first parameter of the static method Parameter: the defined parameter type, and the second parameter: the parameter name.

Constant expression
Use ConstantExpression expressions in expression trees to represent expressions with constant values. , Look at an example, we define a constant of type int 5. And assign the value to the variable i defined above

1 // ParameterExpression represents a named parameter expression.
2 ParameterExpression i = Expression.Parameter (typeof (int), "i");
3 // ParameterExpression j = Expression.Variable (typeof (int), "j");
4 ConstantExpression constExpr = Expression.Constant (5, typeof (int));
5 // Create a System.Linq.Expressions.BinaryExpression for assignment
6 // Indicates an expression containing a binary operator.
7 BinaryExpression binaryExpression = Expression.Assign (i, constExpr);
The first parameter of the Constrant method: constant, the second parameter why the type of constant.

The BinaryExpression expression is mentioned here. This expression identifies the expression containing the binary operator. Similar binary expressions like = and> can be expressed using BinaryExpression expressions.

In debug mode, check the DebugView property of the current expression in the automatic window. This property is very useful when debugging the expression tree:

variable:

constant:

Binary expression:

By observing the above figure, we can see that the DebugView property in the variable debugging mode will display the ParameterExpression variable name with a "$" symbol in front. Then if the parameter has no name, it will be assigned an automatically generated name, such as $ var1 or $ var2 (no more examples here).

Conditional expression
In many cases, we need to use conditional expressions to filter some data, and then return the data that meets the conditions. There are such expressions in the expression to meet your needs.

Common operators

>,> =

<, <=

if .... then: If the condition is met then ...

if ... then ... else: if the condition is met, execute the code, otherwise execute another logic

one example

IfThenElse method

1 public static ConditionalExpression IfThenElse (
2 Expression test,
3 Expression ifTrue,
4 Expression ifFalse
5)
 1 bool test = true;
 2 ConditionalExpression codition = Expression.IfThenElse (
 3 // condition
 4 Expression.Constant (test),
 5 // If the condition is true, call the WriteLine method to output "condition is true"
 6 Expression.Call (
 7 null,
 8 typeof (Console) .GetMethod ("WriteLine", new Type [] {typeof (string)}),
 9 Expression.Constant ("condition is true")
10),
11 // If the condition is false
12 Expression.Call (
13 null,
14 typeof (Console) .GetMethod ("WriteLine", new Type [] {typeof (string)}),
15 Expression.Constant ("condition is false")
16)
17);
18 // Compile the expression tree and output the result
19 Expression.Lambda <Action> (codition) .Compile () ();
Output result

 Example description: The condition test is packaged as a constant expression. Because test is true, the expression of iftrue is executed, and the WriteLine method is called to print out the information.

Assignment expression
=

Take the above example of assigning a value to variable i as an example

1 ParameterExpression i = Expression.Parameter (typeof (int), "i");
2 // ParameterExpression j = Expression.Variable (typeof (int), "j");
3 ConstantExpression constExpr = Expression.Constant (5, typeof (int));
4 // Create a System.Linq.Expressions.BinaryExpression for assignment
5 // Indicates an expression containing a binary operator.
6 BinaryExpression binaryExpression = Expression.Assign (i, constExpr);
+ =

1 BinaryExpression b2 = Expression.AddAssign (i, constExpr);
-=

1 BinaryExpression b3 = Expression.SubtractAssign (i, constExpr);
* =

 BinaryExpression b4 = Expression.MultiplyAssign (i, constExpr);
/ =

1 BinaryExpression b5 = Expression.DivideAssign (i, constExpr);
As an example

 1 ParameterExpression i = Expression.Parameter (typeof (int), "i");
 2 BlockExpression block = Expression.Block (
 3 new [] {i},
 4 // Assign initial value i = 5
 5 Expression.Assign (i, Expression.Constant (5, typeof (int))),
 6 // i + = 5 10
 7 Expression.AddAssign (i, Expression.Constant (5, typeof (int))),
 8 // i- = 5 5
 9 Expression.SubtractAssign (i, Expression.Constant (5, typeof (int))),
10 // i * = 5 25
11 Expression.MultiplyAssign (i, Expression.Constant (5, typeof (int))),
12 // i / = 5 5
13 Expression.DivideAssign (i, Expression.Constant (5, typeof (int)))
14);
15 Console.WriteLine (Expression.Lambda <Func <int >> (block) .Compile () ());
result

Binary operator expression
Partial binary operator expressions are also mentioned above. Operators like addition, subtraction, multiplication and division will not give examples for binary operators. These returned expression trees can be received using BinaryExpression, or using the base class Expression to receive, or more convenient, using the var keyword.

Unary operator expression
Similar to ++,-operator

i ++ is equivalent to i = i + 1, and the operation sequence is that i is increased by 1, and then assigned to i. Use Expression's PostIncrementAssign method in the expression book to perform increment or decrement operations. The return result is of type UnaryExpression, which can also be received using the base class Expression, or var.

Loop expression
Use Expression's Loop method in the expression tree to implement the loop.

Block expression
In the previous article, I also said that you cannot use the Lambda method to create a block-level expression tree, otherwise there will be the following errors

The block-level expression tree can be created through the API, and the Block method of Expression is indispensable. For example, in the above example of addition, subtraction, multiplication and division, multiple Expressions may be included.

So, here is an expression block containing self-incrementing unary expression, loop, and output the result.

Output all even numbers between 1-100.

 1 class Program
 2     {
 3 static void Main (string [] args)
 4 {
 5 // variable i
 6 ParameterExpression i = Expression.Parameter (typeof (int), "i");
 7 // jump out of the loop
 8 LabelTarget label = Expression.Label ();
 9 BlockExpression block = Expression.Block (
10 new [] {i},
11 // Assign initial value to i
12 Expression.Assign (i, Expression.Constant (1, typeof (int))),
13 Expression.Loop (
14 Expression.IfThenElse (
15 // if i <= 100
16 Expression.LessThanOrEqual (i, Expression.Constant (100, typeof (int))),
17 // If true, enter the loop body
18 Expression.Block (
19 Expression.IfThen (
20 // condition i% 2 == 0;
21 Expression.Equal (Expression.Modulo (i, Expression.Constant (2, typeof (int))),
22 Expression.Constant (0, typeof (int))),
23 Expression.Call (typeof (Console) .GetMethod ("WriteLine",
24 new Type [] {typeof (int)}), new [] {i})),
25 // i ++
26 Expression.PostIncrementAssign (i)
27),
28 // if i> 100
29 Expression.Break (label)),
30 label
31));
32 Expression.Lambda <Action> (block) .Compile () ();
33 Console.Read ();
34}
35}
result

to sum up
This article introduces several common types of expressions. Of course, there are many that are not listed, such as switch case and try catch. If you need to create a complex expression tree in your project, the static method of Expression, Block, is essential. I hope that through this study, it will be helpful for you to understand Expression.

Reference article

https://msdn.microsoft.com/zh-cn/library/dd323961(v=vs.110).aspx

https://msdn.microsoft.com/zh-cn/library/bb397951.aspx

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.