Uso algo similar, donde añado filtros a una consulta.
public static Expression<Func<TypeOfParent, bool>> PropertyStartsWith<TypeOfParent, TypeOfPropery>(PropertyInfo property, TypeOfPropery value)
{
var parent = Expression.Parameter(typeof(TypeOfParent));
MethodInfo method = typeof(string).GetMethod("StartsWith",new Type[] { typeof(TypeOfPropery) });
var expressionBody = Expression.Call(Expression.Property(parent, property), method, Expression.Constant(value));
return Expression.Lambda<Func<TypeOfParent, bool>>(expressionBody, parent);
}
uso, para aplicar el filtro contra una propiedad cuyo nombre coincide con llave, y utilizando el valor suministrado, Valor.
public static IQueryable<T> ApplyParameters<T>(this IQueryable<T> query, List<GridParameter> gridParameters)
{
// Foreach Parameter in List
// If Filter Operation is StartsWith
var propertyInfo = typeof(T).GetProperty(parameter.Key);
query = query.Where(PropertyStartsWith<T, string>(propertyInfo, parameter.Value));
}
Y sí, este método funciona con contiene:
public static Expression<Func<TypeOfParent, bool>> PropertyContains<TypeOfParent, TypeOfPropery>(PropertyInfo property, TypeOfPropery value)
{
var parent = Expression.Parameter(typeof(TypeOfParent));
MethodInfo method = typeof(string).GetMethod("Contains", new Type[] { typeof(TypeOfPropery) });
var expressionBody = Expression.Call(Expression.Property(parent, property), method, Expression.Constant(value));
return Expression.Lambda<Func<TypeOfParent, bool>>(expressionBody, parent);
}
Al tener estos 2 ejemplos, se puede entender más fácilmente cómo podemos llamar a varios métodos diferentes por su nombre.
Comience exceptuando algunas respuestas primero, como esta http://stackoverflow.com/questions/1648270/how-to-determine-what-happens-behind-the-scene-in-net/1648306#1648306 y esto http://stackoverflow.com/questions/2331927/linq-to-xml-replace-child-nodes-but-keep-state/2332087#2332087. – Steven
Aquí otro dup: http://stackoverflow.com/questions/1270783/how-to-combine-two-expressions-result-exp1exp2 – Kamarey
Thx para señalar eso, saludos –