2010-03-17 9 views
7

jemand hat eine Vorstellung davon, wie eine .Contains (string) Funktion mit Linq-Ausdrücke zu erstellen, oder auch ein Prädikat erstellen, um dieseLINQ Expression <Func <T, bool>> equavalent von .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); 
} 

zu erreichen Etwas Ähnliches wäre ideal?

+2

Starten Sie zunächst einige Antworten, wie diese http://stackoverflow.com/questions/1648270/how-to-determine-what-happens-behind-the-scene-in-net/1648306#1648306 und dies http://stackoverflow.com/questions/2331927/linq-to-xml-replace-child-nodes-but-keep-state/2332087#2332087. – Steven

+0

Hier noch ein dup: http://stackoverflow.com/questions/1270783/how-to-combine-two-expressions-result-exp1exp2 – Kamarey

+0

Thx für Hinweis darauf, Grüße –

Antwort

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

Hat den Trick, thx –

+0

Um nur einige Klarheit zu geben, wird diese oben erwähnte Lösung nicht funktionieren, wenn Sie es direkt verwenden, habe ich nur einige der Inhalte wie MethodInfo und ParameterExpression verwendet. –

1

Ich benutze etwas ähnliches, wo ich Filter zu einer Abfrage hinzufügen.

Verwendung, um Filter für eine Eigenschaft anzuwenden, deren Name mit Key übereinstimmt und den angegebenen Wert Value verwendet.

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

Und ja, funktioniert diese Methode mit enthält:

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

Durch diese zwei Beispiele mit, Sie können leichter verstehen, wie wir verschiedene Methoden beim Namen nennen können.

Verwandte Themen