LINQ .Containsの発現<のFunc >同等の()
-
20-09-2019 - |
質問
は誰がLINQの式を使用して.Contains(文字列)関数を作成し、あるいはこれを達成するための述語を作成する方法のアイデアを得た。
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);
}
これらの2例を有することにより、あなたがより簡単に、我々は名前によって、様々な異なる方法を呼び出すことができる方法を理解することができます。
所属していません StackOverflow