Created
June 20, 2014 15:46
-
-
Save lnicola/7a8c1f80b21637436a9c to your computer and use it in GitHub Desktop.
Runtime code generation with expression trees (object comparer)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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