2011-12-05 30 views
8
Ben StartsWith, EndsWith ve Contains ile bir dize özelliğini filtrelemek için tip Expression<Func<T, bool>> ifadesini oluşturmak için tip Expression<Func<T, string> bir ifadeyi geçen bir yöntem oluşturmak istiyorum

bu ifadeler gibi yöntemleri:<Func <T, string>>

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

yöntem aşağıdaki gibi görünmelidir:

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

Filtertype sözü operasyonlar (StartsWith, EndsWith, Contains)

+8

Bunun için gidin. Ne denediğini bize bildirin, eğer işe yaramazsa, yardım etmekten mutluluk duyarız. – drdwilcox

cevap

7

üçünü içeren bir enum türü bu deneyin edilir:

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

Bu cevaba "boş olmayan" bir ifade ekledim –

4

Teşekkür @dtb. Bu iyi çalışıyor ve bu durum için böyle bir "null" olmayan bir ifade ekledim:

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); 
    } 
İlgili konular