1

I need to call a lambda expression inside another lambda expression. One expression selects a member and another expression executes something in the selected member (something that returns a Bool)

This question was just the same

Use lambda expression in another lambda expression

I have modify that code a bit (now the type of the selector is generic) but I have a error: "Static method requires null instance, non-static method requires non-null instance."

void Test()
{            
    Expression<Func<Clients, Countries>> sel = client => client.Country; //I select the country of the client
    Expression<Func<Countries, bool>> call = country => country.Cities.Any(); //I want the countrys that have any city

    var test = create( sel, call);            
}

static Expression<Func<TSource, bool>> create<TSource, TMember>(
            Expression<Func<TSource, TMember>> memberSelector,
            Expression<Func<TMember, bool>> methodSelector
        )
{            
    var memberExpression = (MemberExpression)(memberSelector.Body);
    var methodCallExpression = (MethodCallExpression)(methodSelector.Body);

    var input = Expression.Parameter(typeof(TSource));

    //Here fails: Static method requires null instance, non-static method requires non-null instance.
    var call = Expression.Call(
                Expression.MakeMemberAccess(
                                input,
                                memberExpression.Member),

                methodCallExpression.Method,
                methodCallExpression.Arguments);

    return Expression.Lambda<Func<TSource, bool>>(call, input);
}

Thanks in advance!

Community
  • 1
  • 1
Iker
  • 41
  • 1
  • Can you show **the line** where you get that error? – Willem Van Onsem Mar 28 '17 at 11:21
  • The `Country` is _not_ the instance you call the second expression on, it has to be an argument to the second expression. – René Vogt Mar 28 '17 at 11:36
  • 1
    Thanks! That question resolves my question :) http://stackoverflow.com/questions/37602729/convert-linq-expression-obj-obj-prop-into-parent-parent-obj-prop – Iker Mar 28 '17 at 14:16

0 Answers0