LINQ expression with generic property

前端 未结 1 2003
时光取名叫无心
时光取名叫无心 2021-01-06 21:37

My question is related to this one: linq-expression-with-generic-class-properties

This time I would like to get newly created objects which have the id in common. Th

1条回答
  •  礼貌的吻别
    2021-01-06 22:18

    You need to build a new expression representing the condition and pass that to Where:

    public static IEnumerable GetNew(IQueryable objects, TId id, DateTime date, Expression> idSelector)
        where T : class, ISyncable
    {
        var paramExpr = Expression.Parameter(typeof(T));
        var idEqExpr = Expression.Equal(Expression.Invoke(idSelector, paramExpr), Expression.Constant(id));
        var createdPropExpr = Expression.Property(paramExpr, "CreatedDate");
        var gtExpr = Expression.GreaterThan(createdPropExpr, Expression.Constant(date));
        var andExpr = Expression.And(idEqExpr, gtExpr);
    
        var condExpr = Expression.Lambda>(andExpr, paramExpr);
    
        return objects.Where(condExpr);
    }
    

    EDIT: If you know that the idSelector is a property expression, you could extract the referenced property and create a new property expression instead of using Invoke:

    var idProperty = (PropertyInfo)((MemberExpression)idSelector.Body).Member;
    var idEqExpr = Expression.Equal(Expression.Property(paramExpr, idProperty), Expression.Constant(id));
    

    0 讨论(0)
提交回复
热议问题