Lambda表达式在另一个lambda表达式中

时间:2017-03-28 11:19:54

标签: c# linq lambda expression

我需要在另一个lambda表达式中调用lambda表达式。一个表达式选择一个成员,另一个表达式在所选成员中执行某些操作(返回Bool的内容)

这个问题是一样的

Use lambda expression in another lambda expression

我稍微修改了一下代码(现在选择器的类型是通用的)但是我有一个错误:"静态方法需要空实例,非静态方法需要非空实例。"

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);
}

提前致谢!

0 个答案:

没有答案