C# 如何将多个MethodCallExpression联接到一个表达式中?

C# 如何将多个MethodCallExpression联接到一个表达式中?,c#,linq,lambda,expression,C#,Linq,Lambda,Expression,我有一个查询,需要对其应用n个筛选器。然而,我必须使用表达式。到目前为止,我已经为每个过滤器构造了表达式,效果非常好。问题是我想将这些过滤器合并到一个表达式中,以便将其用作LINQ的.Where()的参数 过滤代码: //Filters could slightly differ in functionality private Expression<Func<T, bool>> StringPropertyContains<T>(Filte

我有一个查询,需要对其应用n个筛选器。然而,我必须使用表达式。到目前为止,我已经为每个过滤器构造了表达式,效果非常好。问题是我想将这些过滤器合并到一个表达式中,以便将其用作LINQ的.Where()的参数

过滤代码:

    //Filters could slightly differ in functionality 
    private Expression<Func<T, bool>> StringPropertyContains<T>(Filter filter)
    {
        if (filter == null)
        {
            throw new ArgumentNullException(nameof(filter));
        }

        if (typeof(T).GetProperties().FirstOrDefault(pi => pi.Name.Equals(filter.PropertyName, StringComparison.OrdinalIgnoreCase)) == null)
        {
            throw new ArgumentNullException($"Type {typeof(T)} does not contain property {filter.PropertyName}");
        }

        var propertyInfo = typeof(T).GetProperty(filter.PropertyName);
        var param = Expression.Parameter(typeof(T));
        var member = Expression.MakeMemberAccess(param, propertyInfo);
        var constant = Expression.Constant(filter.Value, typeof(filter.Type));
        var methodInfo = typeof(filter.Type).GetMethod(filter.Method, new Type[] { typeof(filter.Type) });
        var body = Expression.Call(member, methodInfo, constant);

        return Expression.Lambda<Func<T, bool>>(body, param);
    }

    private Expression<Func<T, bool>> Filter<T>(T t)
    {
        //TODO join filters while each filter should have its different parameter
        //the parameter is currently constructed in the object and is accessible via property Filter[] ParsedFilter
    }
预期用途:

IQueryable<T> q = query.Where(this.Filter)
IQueryable q=query.Where(this.Filter)

老实说,我对这个问题感到非常头痛,因为我对表达式还很陌生。因此,感谢您提供的帮助。

您不能将类作为参数传递给Where子句,但是您可以使用Linq表达式实现您想要的:

Expression<Func<T, bool>> filter = q => q.type == filter.Type && q.Value == filter.Value;

var x = query.Where(filter);
expressionfilter=q=>q.type==filter.type&&q.Value==filter.Value;
var x=查询。其中(过滤器);

您是否在询问如何组合多个
表达式?如果组合符是
&&
(AND),您可以简单地在其中链接多个
。或者使用一些谓词生成器。
Expression<Func<T, bool>> filter = q => q.type == filter.Type && q.Value == filter.Value;

var x = query.Where(filter);