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
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));