Skip to content

Instantly share code, notes, and snippets.

@JakeGinnivan
Created March 17, 2014 08:23
Show Gist options
  • Select an option

  • Save JakeGinnivan/9595723 to your computer and use it in GitHub Desktop.

Select an option

Save JakeGinnivan/9595723 to your computer and use it in GitHub Desktop.
Lambda shiz
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