ExpressionTree-IterationExpression

CSharp · Console

/Program.cs

using System;
using System.Linq.Expressions;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
					
public class Program
{
	public static void Main()
	{
		
		Console.WriteLine("****************** C# Equivalent Output **************************\n\n");
		
		int cValue = 6;

		var cResult = 1;
		while (cValue > 1)
		{
		    cResult = cResult * cValue;
		    cValue--;
		}
		Console.WriteLine(cResult);

		
		Console.WriteLine("\n\n***************** Expression Tree Output **************************\n\n");
		
		
		ParameterExpression value = Expression.Parameter(typeof(int), "value");

		// Creating an expression to hold a local variable. 
		ParameterExpression result = Expression.Parameter(typeof(int), "result");

		// Creating a label to jump to from a loop.
		LabelTarget label = Expression.Label(typeof(int));
		
		ConditionalExpression ifThenElseExpr = Expression.IfThenElse(
		    Expression.GreaterThan(value, Expression.Constant(1)),
		    Expression.MultiplyAssign(result,
		        Expression.PostDecrementAssign(value)),
		    Expression.Break(label, result)
			);

		LoopExpression loop = Expression.Loop(ifThenElseExpr, label);

		// Creating a method body.
		BlockExpression block = Expression.Block(
		    new[] { result },
		    Expression.Assign(result, Expression.Constant(1)),
		    loop
			);

		// Compile and run an expression tree.
		var factorial = Expression.Lambda<Func<int, int>>(block, value).Compile();

		Console.WriteLine(factorial(6));
	}
}
;