在C#中使用动态或表达式

Ped*_*ram 2 c# linq expression

我在我的程序中使用动态过滤器,如下面的解决方案:

public static IQueryable<T> MyFilter<T>(this IQueryable<T> queryable) where T : class ,IModel
{
        var someIds = new int[]{1,2,3,4,5};
        var userId = 2;

        Expression<Func<T, bool>> predicate1 = e => someIds.Contains(e.Id);
        Expression<Func<T, bool>> predicate2 = e => e.UserId==userId;
        Expression<Func<T, bool>> predicate3 = e => e.CreatedDate != null;

        var pred1 = Expression.Lambda<Func<T, bool>>(System.Linq.Expressions.Expression.Or(predicate1, predicate2));
        var pred2 = Expression.Lambda<Func<T, bool>>(System.Linq.Expressions.Expression.Or(pred1, predicate3));


        var result = queryable
            .Where(pred2);

        return result;
    }
Run Code Online (Sandbox Code Playgroud)

IModel是这样的:

Public interface IModel{
   int Id { get; set; }
   int UserId { get; set; }
   DateTime? CreatedDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到此错误:

二进制运算符Or未定义类型'System.Func 2[AnyClass,System.Boolean]' and 'System.Func2 [AnyClass,System.Boolean]'.

在这一行:

var pred1 = Expression.Lambda<Func<T, bool>>(System.Linq.Expressions.Expression.Or(predicate1, predicate2));
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?

事先欣赏任何帮助

xan*_*tos 5

正如我在评论中所写,有两个不同的问题:

  • 你必须使用Expression.OrElse,因为Expression.Or|运营商.

  • 但真正的问题是,你不能加入Lambda表达式(predicate1,2,3以这种方式).加入表情是复杂的,因为输入参数predicate1,2,3是不同的(就好像它是e1,e2,e3而不是e),并且pred1pred2将有一个e4e5输入参数,所以你必须要一些表达式来替换.

解决方案:

// Note that we only need the Body!
Expression pred1 = Expression.OrElse(Expression.OrElse(predicate1.Body, predicate2.Body), predicate3.Body);

// We change all the predicate2.Parameters[0] to predicate1.Parameters[0] and
// predicate3.Parameters[0] to predicate1.Parameters[0]

var replacer = new SimpleExpressionReplacer(
    /* from */ new[] { predicate2.Parameters[0], predicate3.Parameters[0] }, 
    /* to */ new[] { predicate1.Parameters[0], predicate1.Parameters[0] });

pred1 = replacer.Visit(pred1);

// We use for the new predicate the predicate1.Parameters[0]
var pred2 = Expression.Lambda<Func<T, bool>>(pred1, predicate1.Parameters[0]);

var result = queryable.Where(pred2);
Run Code Online (Sandbox Code Playgroud)

SimpleExpressionReplacer:

// A simple expression visitor to replace some nodes of an expression 
// with some other nodes
public class SimpleExpressionReplacer : ExpressionVisitor
{
    public readonly Dictionary<Expression, Expression> Replaces;

    public SimpleExpressionReplacer(Dictionary<Expression, Expression> replaces)
    {
        Replaces = replaces;
    }

    public SimpleExpressionReplacer(IEnumerable<Expression> from, IEnumerable<Expression> to)
    {
        Replaces = new Dictionary<Expression, Expression>();

        using (var enu1 = from.GetEnumerator())
        using (var enu2 = to.GetEnumerator())
        {
            while (true)
            {
                bool res1 = enu1.MoveNext();
                bool res2 = enu2.MoveNext();

                if (!res1 || !res2)
                {
                    if (!res1 && !res2)
                    {
                        break;
                    }

                    if (!res1)
                    {
                        throw new ArgumentException("from shorter");
                    }

                    throw new ArgumentException("to shorter");
                }

                Replaces.Add(enu1.Current, enu2.Current);
            }
        }
    }

    public SimpleExpressionReplacer(Expression from, Expression to)
    {
        Replaces = new Dictionary<Expression, Expression> { { from, to } };
    }

    public override Expression Visit(Expression node)
    {
        Expression to;

        if (node != null && Replaces.TryGetValue(node, out to))
        {
            return base.Visit(to);
        }

        return base.Visit(node);
    }
}
Run Code Online (Sandbox Code Playgroud)