Reputation: 2709
I will first show a fully working equivalent that does not use expression-trees:
public class ClassUsingFuncs
{
public SomeClass SomeProperty { get; set; }
public void DoSomethingUsingFuncWithoutArgument(Func<bool> funcWithoutArgument)
{
}
public void DoSomethingUsingFuncWithArgument(Func<SomeClass, bool> funcWithArgument)
{
Func<bool> funcWithoutArgument = () => funcWithArgument(SomeProperty);
DoSomethingUsingFuncWithoutArgument(funcWithoutArgument);
}
}
How do I achieve the equivalent for this when using expression-trees? It's no problem if I will need LINQKit or some other library to achieve this.
public class ClassUsingExpressionTrees
{
public SomeClass SomeProperty { get; set; }
public void DoSomethingUsingExpressionWithoutArgument(Expression<Func<bool>> expressionWithoutArgument)
{
}
public void DoSomethingUsingExpressionWithArgument(Expression<Func<SomeClass, bool>> expressionWithArgument)
{
Expression<Func<bool>> expressionWithoutArgument = ?
DoSomethingUsingExpressionWithoutArgument(expressionWithoutArgument);
}
}
Upvotes: 2
Views: 172
Reputation: 144206
public void DoSomethingUsingExpressionWithArgument(Expression<Func<SomeClass, bool>> expressionWithArgument)
{
var thisExpr = Expression.Constant(this);
var pExpr = Expression.Property(thisExpr, "SomeProperty");
var invokeExpr = Expression.Invoke(expressionWithArgument, pExpr);
Expression<Func<bool>> expressionWithoutArgument = Expression.Lambda<Func<bool>>(invokeExpr);
DoSomethingUsingExpressionWithoutArgument(expressionWithoutArgument);
}
Upvotes: 1