2010-03-17 65 views
7

有没有人拿到了如何创建使用LINQ表达式。载有(串)功能,甚至创造一个谓词来完成这个LINQ表达<Func键<T, bool>>。载有()

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

一个想法equavalent与此相似的东西会是理想的吗?

+2

开始除了一些答案第一,如这一个http://stackoverflow.com/questions/1648270/how-to-determine-what-happens-behind-the-scene-in-net/1648306#1648306和这个http://stackoverflow.com/questions/2331927/linq-to-xml-replace-child-nodes-but-keep-state/2332087#2332087。 – Steven 2010-03-17 09:27:30

+0

在这里另一个dup:http://stackoverflow.com/questions/1270783/how-to-combine-two-expressions-result-exp1exp2 – Kamarey 2010-03-17 09:38:39

+0

thx为指出,关心 – 2010-03-17 09:41:41

回答

6
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"); 
+0

诀窍,thx – 2010-03-17 10:34:25

+0

只是为了清楚起见,如果直接使用上述解决方案,上述解决方案将不起作用,我只使用了一些内容,如MethodInfo和ParameterExpression。 – 2010-03-18 06:57:20

1

我使用类似的东西,在那里我添加过滤器查询。

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

用法,对名称与Key匹配的属性应用过滤器,并使用提供的值Value。

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个例子,你可以更容易地了解我们如何可以通过名字调用各种不同的方法。

相关问题