using System.Linq.Expressions;
using System.Collections;
using System.Collections.Generic;
public static void Main()
var list = new List<int>() { 10, 20, 30 };
Console.WriteLine("****************** C# Equivalent Output **************************\n\n");
foreach (var item in list)
Console.WriteLine("\n\n***************** Expression Tree Output **************************\n\n");
var collection = Expression.Parameter(typeof(List<int>), "collection");
var loopVar = Expression.Parameter(typeof(int), "loopVar");
var loopBody = Expression.Call(typeof(Console).GetMethod("WriteLine", new[] { typeof(int) }), loopVar);
var loop = ForEach(collection, loopVar, loopBody);
var results = Expression.Lambda<Action<List<int>>>(loop, collection).Compile();
public static Expression ForEach(Expression collection, ParameterExpression loopVar, Expression loopContent)
var elementType = loopVar.Type;
var enumerableType = typeof(IEnumerable<>).MakeGenericType(elementType);
var enumeratorType = typeof(IEnumerator<>).MakeGenericType(elementType);
var enumeratorVar = Expression.Variable(enumeratorType, "enumerator");
var getEnumeratorCall = Expression.Call(collection, enumerableType.GetMethod("GetEnumerator"));
var enumeratorAssign = Expression.Assign(enumeratorVar, getEnumeratorCall);
var moveNextCall = Expression.Call(enumeratorVar, typeof(IEnumerator).GetMethod("MoveNext"));
var breakLabel = Expression.Label("LoopBreak");
var ifThenElseExpr = Expression.IfThenElse(
Expression.Equal(moveNextCall, Expression.Constant(true)),
Expression.Block(new[] { loopVar },
Expression.Assign(loopVar, Expression.Property(enumeratorVar, "Current")),
Expression.Break(breakLabel)
var loop = Expression.Loop(ifThenElseExpr, breakLabel);
var block = Expression.Block(new[] { enumeratorVar },