linq expression > equavalent of .contains ()
-
20-09-2019 - |
문제
LINQ 표현식을 사용하여 .crantains (String) 함수를 만드는 방법에 대한 아이디어가 있거나이를 달성하기 위해 술어를 만드는 아이디어가 있습니까?
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);
}
이것에 대해 비슷한 것이 이상적입니까?
해결책
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");
다른 팁
나는 쿼리에 필터를 추가하는 비슷한 것을 사용합니다.
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);
}
사용법, 이름이 키와 일치하는 속성에 필터를 적용하고 공급 된 값, 값을 사용합니다.
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));
}
그렇습니다.이 방법은 다음과 같이 작동합니다.
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);
}
이 두 가지 예를 가지고 있으면 다양한 다른 방법을 이름으로 어떻게 호출 할 수 있는지 더 쉽게 이해할 수 있습니다.
제휴하지 않습니다 StackOverflow