2011-12-05 10 views
8

Voglio creare un metodo passando un espressione del tipo Expression<Func<T, string> per creare un'espressione di tipo Expression<Func<T, bool>> per filtrare una proprietà stringa con il StartsWith, EndsWith e Contains metodi come queste espressioni:creare un'espressione Linq con StartsWith, EndsWith e contiene il superamento di un Expression <Func <T, string>>

.Where(e => e.MiProperty.ToUpper().StartsWith("ABC")); 
.Where(e => e.MiProperty.ToUpper().EndsWith("XYZ")); 
.Where(e => e.MiProperty.ToUpper().Contains("MNO")); 

il metodo dovrebbe essere simile:

public Expression<Func<T, bool>> AddFilterToStringProperty<T>(Expresssion<Func<T, string>> pMyExpression, string pFilter, FilterType pFiltertype) 

dove FilterType è un tipo enum che contiene tre operazioni menzionate (StartsWith, EndsWith, Contains)

+8

Vai per questo. Fateci sapere cosa provate, e se non funziona, saremo felici di aiutarvi. – drdwilcox

risposta

7

Prova questo:

public static Expression<Func<T, bool>> AddFilterToStringProperty<T>(
    Expression<Func<T, string>> expression, string filter, FilterType type) 
{ 
    return Expression.Lambda<Func<T, bool>>(
     Expression.Call(
      expression.Body, 
      type.ToString(), 
      null, 
      Expression.Constant(filter)), 
     expression.Parameters); 
} 
+0

Ho aggiunto un'espressione "non nulla" a questa risposta –

4

Grazie @dtb. Funziona bene e ho aggiunto un'espressione "non nulla" per questo caso:

public static Expression<Func<T, bool>> AddFilterToStringProperty2<T>(
         Expression<Func<T, string>> expression, string filter, FilterType type) 
    { 
     var vNotNullExpresion = Expression.NotEqual(
           expression.Body, 
           Expression.Constant(null)); 

     var vMethodExpresion = Expression.Call(
       expression.Body, 
       type.ToString(), 
       null, 
       Expression.Constant(filter)); 

     var vFilterExpresion = Expression.AndAlso(vNotNullExpresion, vMethodExpresion); 

     return Expression.Lambda<Func<T, bool>>(
      vFilterExpresion, 
      expression.Parameters); 
    } 
Problemi correlati