Created
March 17, 2014 08:23
-
-
Save JakeGinnivan/9595723 to your computer and use it in GitHub Desktop.
Lambda shiz
This file contains hidden or 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
| void Main() | |
| { | |
| GetExpression().Compile()(new Foo { Bar = new Bar { Abc = "A" }}).Dump(); | |
| GetExpression().Compile()(new Foo { Bar = new Bar { Abc = "B" }}).Dump(); | |
| } | |
| Expression<Func<Foo, bool>> GetExpression() | |
| { | |
| // Method takes Foo and uses an expression to first retrieve Bar | |
| // Then it uses that to verify if Bar.Abc is equal to something | |
| Expression<Func<Foo, Bar>> getBarExpression = foo => foo.Bar; | |
| Expression<Func<Bar, bool>> verifyBar = bar => bar.Abc != "B"; | |
| var parameterExpression = Expression.Parameter(typeof(Foo), "foo"); | |
| var parameterExpression2 = Expression.Parameter(typeof(Bar), "bar"); | |
| // First invoke foo => foo.Bar to get Bar | |
| var barResultExpression = Expression.Invoke(getBarExpression, parameterExpression); | |
| var resultExpression = Expression.Invoke(verifyBar, barResultExpression); | |
| // Give me the combined expression | |
| return Expression.Lambda<Func<Foo, bool>>(resultExpression, parameterExpression); | |
| } | |
| // Define other methods and classes here | |
| class Foo | |
| { | |
| public Bar Bar { get; set;} | |
| } | |
| class Bar | |
| { | |
| public string Abc {get;set;} | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment