lnicola
6/20/2014 - 3:46 PM

Runtime code generation with expression trees (object comparer)

Runtime code generation with expression trees (object comparer)

using System;
using System.Linq;
using System.Linq.Expressions;

namespace ConsoleApplication1
{
    public class Foo
    {
        public int A { get; set; }
        public Bar Bar;
    }

    public class Bar
    {
        public int? B { get; set; }
    }

    class Program
    {
        static Func<object, bool> GenerateComparer(Type valueType, string propertyPath, string targetValue)
        {
            var argumentParameter = Expression.Parameter(typeof(object), "argument");
            return Expression.Lambda<Func<object, bool>>(
                        Expression.Equal(
                            Expression.Call(
                                propertyPath.Split('.').Aggregate<string, Expression>(Expression.Convert(argumentParameter, valueType), Expression.PropertyOrField),
                                typeof(object).GetMethod("ToString")),
                            Expression.Constant(targetValue)),
                    argumentParameter)
                   .Compile();
        }

        static void Main()
        {
            var foo = new Foo { A = 43, Bar = new Bar { B = 10 } };
            Console.WriteLine(GenerateComparer(typeof(Foo), "A", "43")(foo));
            Console.WriteLine(GenerateComparer(typeof(Foo), "Bar.B", "10")(foo));
        }
    }
}