Skip to content

Instantly share code, notes, and snippets.

@lnicola
Created June 20, 2014 15:46
Show Gist options
  • Save lnicola/7a8c1f80b21637436a9c to your computer and use it in GitHub Desktop.
Save lnicola/7a8c1f80b21637436a9c to your computer and use it in GitHub Desktop.
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));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment