Expression trees and advanced queries in C# 03

CSharp · Console

/Program.cs

using System;
using System.Linq.Expressions;
					
public class Program
{
	public static void Main()
	{
		  var parameter = Expression.Parameter(typeof(Bar), "a");
			
			var bazProp = typeof(Bar).GetProperty(nameof(Bar.Baz));
            var body = Expression.GreaterThan(
                Expression.MakeMemberAccess(parameter, bazProp),
                Expression.Constant(55));

            Expression<Func<Bar, bool>> foo2 
				= Expression.Lambda<Func<Bar, bool>>(body, new[] { parameter });
		
		 var result1 = foo2.Compile().Invoke(new Bar() { Baz = 50 }); //false
 	     var result2 = foo2.Compile().Invoke(new Bar() { Baz = 60 }); //true
		
		Console.WriteLine(result1);
		Console.WriteLine(result2);
	}
	
    public class Bar
    {
        public int Baz { get; set; }
    }
}
;