How do I combine LINQ expressions into one?

前端 未结 3 1219
天涯浪人
天涯浪人 2020-12-10 01:39

I\'ve got a form with multiple fields on it (company name, postcode, etc.) which allows a user to search for companies in a database. If the user enters values in more than

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 02:19

    You can use Enumerable.Aggregate combined with Expression.AndAlso. Here's a generic version:

    Expression> AndAll(
        IEnumerable>> expressions) {
    
        if(expressions == null) {
            throw new ArgumentNullException("expressions");
        }
        if(expressions.Count() == 0) {
            return t => true;
        }
        Type delegateType = typeof(Func<,>)
                                .GetGenericTypeDefinition()
                                .MakeGenericType(new[] {
                                    typeof(T),
                                    typeof(bool) 
                                }
                            );
        var combined = expressions
                           .Cast()
                           .Aggregate((e1, e2) => Expression.AndAlso(e1, e2));
        return (Expression>)Expression.Lambda(delegateType, combined);
    }
    

    Your current code is never assigning to combined:

    expr => Expression.And(combined, expr);
    

    returns a new Expression that is the result of bitwise anding combined and expr but it does not mutate combined.

提交回复
热议问题