LINQ Expression > équivalent de .Contains ()
-
20-09-2019 - |
Question
Quelqu'un at-il eu une idée de la façon de créer une fonction .Contains (string) en utilisant des expressions Linq, ou même créer un prédicat pour y parvenir
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
}
Quelque chose simular ce serait idéal?
La solution
public static Expression<Func<string, bool>> StringContains(string subString)
{
MethodInfo contains = typeof(string).GetMethod("Contains");
ParameterExpression param = Expression.Parameter(typeof(string), "s");
return Expression.Call(param, contains, Expression.Constant(subString, typeof(string)));
}
...
// s => s.Contains("hello")
Expression<Func<string, bool>> predicate = StringContains("hello");
Autres conseils
J'utilise quelque chose de similaire, où ajouter des filtres à une requête.
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);
}
Utilisation, d'appliquer le filtre contre une propriété dont le nom correspond à la clé, et en utilisant la valeur fournie, la valeur.
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));
}
Et oui, cette méthode fonctionne avec contient:
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);
}
En ayant ces 2 exemples, vous pouvez plus facilement comprendre comment nous pouvons appeler différentes méthodes par nom.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow