Created
November 20, 2013 20:12
-
-
Save KyleGobel/7570167 to your computer and use it in GitHub Desktop.
Convert Types of an Expression
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
class Foo { | |
public int Value { get; set; } | |
} | |
class Bar { | |
public int Value { get; set; } | |
} | |
static class Program { | |
static void Main() { | |
Expression<Func<Foo, bool>> predicate = | |
x => x.Value % 2 == 0; | |
Expression<Func<Bar, Foo>> convert = | |
bar => new Foo { Value = bar.Value }; | |
var param = Expression.Parameter(typeof(Bar), "bar"); | |
var body = Expression.Invoke(predicate, | |
Expression.Invoke(convert, param)); | |
var lambda = Expression.Lambda<Func<Bar, bool>>(body, param); | |
// test with LINQ-to-Objects for simplicity | |
var func = lambda.Compile(); | |
bool withOdd = func(new Bar { Value = 7 }), | |
withEven = func(new Bar { Value = 12 }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment