如何创建动态Lambda表达式

时间:2013-03-19 17:34:46

标签: c# expression lambda

我有一个问题,如何添加其他过滤器,我必须验证是否已选中?

private Expression < Func < Entity.Modelos.Flux, bool >> Filter() {
    var dateStart = dtpDateStart.Value.Date;
    var dateEnd = dtpDateEnd.Value.Date;

    Expression < Func < Entity.Modelos.Flux, bool >> expr = null;

    expr = f = > f.DatFlux >= dateStart.Date && f.DatFlux <= dateEnd.Date;

    if (txtDescription.Text != String.Empty) {
        //add filter
    }

    return expr;
}

更新:我将在此函数中使用表达式:

public virtual IQueryable < T > Filter(Expression < Func < T, bool >> expressao) {
    return DbSet.Where(expressao).AsQueryable < T > ();
}

我试图做的是这个但是带有表达式

public List < Users > GetUsers(int ? id, string name) {
    using(DBContext ctx = new DBContext()) {
        IQueryable query = ctx.Usuarios;
        if (id.HasValue)
            query = query.Where(x = > x.ID == id);

        if (!string.IsNullOrEmpty(name))
            query = query.Where(x = > x.Name.StartsWith(name));

        return query.ToList();

    }
}

5 个答案:

答案 0 :(得分:0)

如果这只是您的要求的演示,那么您可以使用Expression Trees命名空间创建和修改System.Linq.Expressions

但是,对于您的问题,使用EF可能更容易:

bool filterDescription = !String.IsNullOrEmpty( txtDescription.Text );

expr = f =>
  (
    ( f.DatFlux >= dateStart.Date && f.DatFlux <= dateEnd.Date )
    &&
    ( !filterDescription || ... add filter ... )
  )
;

或正常的C#:

if ( String.IsNullOrEmpty( txtDescription.Text ) )
{
  expr = f => f.DatFlux >= dateStart.Date && f.DatFlux <= dateEnd.Date;
}
else
{
  expr = f => f.DatFlux >= dateStart.Date && f.DatFlux <= dateEnd.Date
    &&
    ... add filter ...
  ;
}

答案 1 :(得分:0)

好的,这里有一个关于如何嵌入lambda语句的示例。这不是你的榜样,但是你在这里:

Func<int, int, EventHandler> makeHandler =
    (dx, dy) => (sender, e) => {
        var btn = (Button) sender;
        btn.Top += dy;
        btn.Left += dx;
    };

btnUp.Click += makeHandler(0, -1);
btnDown.Click += makeHandler(0, 1);
btnLeft.Click += makeHandler(-1, 0);
btnRight.Click += makeHandler(1, 0);

答案 2 :(得分:0)

It is simple.Visit this link

棘手的是调用OrderByAlias - 使用MakeGenericMethod可能就是这样,如上面的链接所示。

答案 3 :(得分:0)

尝试这种方式:

private Expression<Func<Entity.Modelos.Flux, bool>> Filter()
{
    var dateStart = dtpDateStart.Value.Date;
    var dateEnd = dtpDateEnd.Value.Date;

    Func<Entity.Modelos.Flux, bool> expr = null;

    expr = f => f.DatFlux >= dateStart.Date && f.DatFlux <= dateEnd.Date;

    if(txtDescription.Text != String.Empty)
    {
       expr = f => expr(f) && f.Title.Equals(txtDescription.Text); // ← Your additional filter
    }

    return f => expr(f);
}

答案 4 :(得分:0)

继承自ExpressionVisitor

public class MyVisitor: ExpressionVisitor
{
    private LambdaExpression visitor;
    public Expression Modify(Expression expression, LambdaExpression visitor)
    {
        this.visitor = visitor;
        return Visit(expression);
    }

    protected override Expression VisitBinary(BinaryExpression b)
    {
        var binary = visitor.Body as BinaryExpression;

        return Expression.MakeBinary(ExpressionType.AndAlso, b, binary, b.IsLiftedToNull, b.Method);
    }
}

您的Filter()方法可能如下所示

    private Expression<Func<Entity.Modelos.Flux, bool>> Filter()
    {
        var dateStart = dtpDateStart.Value.Date;
        var dateEnd = dtpDateEnd.Value.Date;
        var description = txtDescription.Text;

        Expression<Func<Entity.Modelos.Flux, bool>> expr = null;

        expr = f => f.DatFlux >= dateStart.Date && f.DatFlux <= dateEnd.Date;

        if (description != String.Empty)
        {
            //add filter
            Expression<Func<Entity.Modelos.Flux, bool>> other = f => f.Description == description;

            var modifier = new MyVisitor();
            expr = (Expression<Func<Entity.Modelos.Flux, bool>>)modifier.Modify((Expression)expr, (LambdaExpression)other);
        }

        return expr;
    }

example

请查看以下内容以获取更多信息

How to: Modify Expression Trees (C# and Visual Basic)