2012-07-20 51 views
0
static class QueryableExtensions 
{ 
private static MethodInfo StringContainsMethod; 
private static MethodInfo StringStartsWithMethod; 
static QueryableExtensions() 
{ 
    Type[] singleStringParam = new[] { typeof(string) }; 
    StringContainsMethod = typeof(string).GetMethod("Contains", singleStringParam); 
    StringStartsWithMethod = typeof(string).GetMethod("StartsWith", singleStringParam); 
} 
public static IQueryable<T> AppendTextFilter<T>(this IQueryable<T> queryable, Expression<Func<T, string>> memberSelector, string condition, string value) 
{ 
    Expression expression = null; 
    switch (condition) 
    { 
     case "StartsWith": 
      expression = Expression.Call(memberSelector.Body, StringStartsWithMethod, Expression.Constant(value)); 
      break; 
     case "Equals": 
      expression = Expression.Equal(memberSelector.Body, Expression.Constant(value)); 
      break; 
     case "Contains": 
      expression = Expression.Call(memberSelector.Body, StringContainsMethod, Expression.Constant(value)); 
      break; 
     default: 
      throw new NotSupportedException(string.Format("'{0}' is not a supported condition", condition)); 
    } 
    var lambda = Expression.Lambda<Func<T, bool>>(expression, memberSelector.Parameters); 
    return queryable.Where(lambda); 
} 
} 

當我在谷歌上搜索時,我得到了上面的類。好吧,它真的幫了我很多,但它仍然不能滿足我的需要。
問題是它只能處理「字符串」類型的字段。正如你在上面的代碼塊中看到的那樣,該方法只能用T,字符串進行處理。
如何在一種方法中處理我想要的任何類型?配置動態linq express

回答

0

好吧,這個想法是用一種泛型替換字符串,這種方式。

public static IQueryable<T> AppendTextFilter<T, TValue>(
     this IQueryable<T> queryable, 
     Expression<Func<T, TValue>> memberSelector, 
     string condition, 
     TValue value) 

但隨着你的樣品,這並沒有太大的意義,因爲StartsWith,例如,可以只被應用如果TValue類型爲string ...

+0

好了,謝謝你。我不是很熟悉字典值。它真的幫助我。 – user1539984 2012-07-20 10:11:09

+0

@ user1539984字典價值?你什麼意思 ? – 2012-07-20 10:15:01

+0

我犯了一個錯誤。它應該是Dictionary Type。 – user1539984 2012-07-27 06:55:26