Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Using System. LINQ. expressions;
Using System. collections;
Namespace Consoleapp
{
/// <Summary>
/// By rhythmk expression Learning
/// Refer: Http://rednaxelafx.iteye.com/blog/247270
/// </Summary>
Class Program
{
Static Void Main (String [] ARGs)
{
Constant ();
Method1 ();
Int [] Array = New Int [] { 12 , 12 , 35 , 5 , 3 , 4 , 4 , 35 , 3 , 4 , 3 , 0 };
// Lambda
Defaultexpress (array );
// Create from Expression Tree
Createexpress (array );
Console. Read ();
}
Static Void Defaultexpress ( Int [] _ Array)
{
Expression <func < Int [], Int > Exp = array => (array! = Null & Amp; array. Length & gt; 0 )? 2 * (Array [ 0 ] + 5 ):- 1 ;
VaR Expcompile = exp. Compile ();
Console. Write (expcompile (_ array ));
}
Static Void Createexpress ( Int [] _ Array)
{
Parameterexpression parameterexp = expression. parameter ( Typeof ( Int []), " Array " );
Expression <func <Int [], Int > Exp = expression. Lambda <func < Int [], Int > (
Expression. condition (
Expression. andalso (
Expression. notequal (
Parameterexp,
Expression. Constant ( Null )
),
Expression. greaterthan (
Expression. arraylength (parameterexp ),
Expression. Constant ( 0 , Typeof ( Int ))
)
),
Expression. Multiply (
Expression. Constant ( 2 , Typeof ( Int )),
Expression. Add (
Expression. Constant ( 5 , Typeof ( Int )),
Expression. arrayindex (
Parameterexp,
Expression. Constant ( 0 , Typeof ( Int )))
)
),
Expression. Constant (- 1 , Typeof ( Int ))
), New Parameterexpression [] {parameterexp });
VaR Result = exp. Compile ();
Console. Write (result (_ array ));
}
Static Void Constant ()
{
Expression <func < Int > Exp = expression. Lambda <func < Int > (
Expression. Constant (
1 ,
Typeof ( Int )
),
New Parameterexpression [] {}
);
VaR Q = exp. Compile ();
Console. Write ( " Result: " + Q ());
}
# Region
Static Void Method1 ()
{
Parameterexpression _ Param = expression. parameter ( Typeof ( Int ), " A " );
Expression <func <Int , Int > Exp = expression. Lambda <func < Int , Int > (
Expression. Add (_ Param,
Expression. Constant ( 2 , Typeof ( Int ))
),
New Parameterexpression [] {_ Param}
);
VaR Q = exp. Compile ();
Console. Write ( " Result: " + Q ( 12 )); // Result: 14
Constantexpression exp1 = expression. Constant ( 2 , Typeof ( Int ));
Binaryexpression binaryexp = expression. Add (exp1, _ PARAM );
Expression <func < Int , Int > Exp2 = expression. Lambda <func < Int , Int >>( Binaryexp, _ PARAM );
VaR Q2 = exp2.compile ();
Console. Write ( " Result: " + Q2 ( 12 )); // Result: 14
}
# Endregion
}
}