2011-03-27 62 views
5

我想做一個方法,像這樣的簽名:參數LINQ表達式幫助

Expression<Func<TSource, bool>> CreatePropertyFilter<TSource>(Expression<Func<TSource, string>> selector, string value, TextMatchMode matchMode); 

基本上,它需要一個屬性選擇器(例如:p = p.Name),一個字符串值,並且可以StartsWith一個枚舉值,EndsWithContainsExact;用於文本匹配選項。

如何以LINQ2Entities可以理解的方式實現該方法?我已經實現了使用這樣的嵌套調用表達式的方法:

Expression<Func<string, bool>> comparerExpression; 

switch (matchMode) 
{ 
    case TextMatchMode.StartsWith: 
     comparerExpression = p => p.StartsWith(value); 
     break; 
    case TextMatchMode.EndsWith: 
     comparerExpression = p => p.EndsWith(value); 
     break; 
    case TextMatchMode.Contains: 
     comparerExpression = p => p.Contains(value); 
     break; 
    default: 
     comparerExpression = p => p.Equals(value); 
     break; 
} 

var equalityComparerParameter = Expression.Parameter(typeof(IncomingMail), null); 
var equalityComparerExpression = Expression.Invoke(comparerExpression, Expression.Invoke(selector, equalityComparerParameter)); 
var equalityComparerPredicate = Expression.Lambda<Func<IncomingMail, bool>>(equalityComparerExpression, equalityComparerParameter); 

的問題是,Linq2Entities不支持調用表達式。

對此有何建議?

謝謝!

回答

5

從本質上講,給定一個選擇:

input => input.Member 

您正在建造像謂詞表達式:通過使用其

input => selector(input).Method(value) 

相反, '擴大' 出來,選擇的表達(一MemberExpression),構建類似的東西:

input => input.Member.Method(value) 

這將是這樣的:

private static Expression<Func<TSource, bool>> CreatePropertyFilter<TSource> 
    (Expression<Func<TSource, string>> selector, 
    string value, 
    TextMatchMode matchMode) 
{ 
    // Argument-checking here.  

    var body = selector.Body as MemberExpression; 

    if (body == null) 
     throw new ArgumentException("Not a MemberExpression.");  

    // string.StartsWith/EndsWith etc. depending on the matchMode. 
    var method = typeof(string) 
       .GetMethod(GetMethodName(matchMode), new[] { typeof(string) }); 

    // input.Member.method(value) 
    var compEx = Expression.Call(body, method, Expression.Constant(value)); 

    // We can reuse the parameter of the source. 
    return Expression.Lambda<Func<TSource, bool>>(compEx, selector.Parameters); 
} 

當翻譯的方法是:

// I really don't like this enum. 
// Why not explicitly include Equals as a member? 
private static string GetMethodName(TextMatchMode mode) 
{ 
    switch (mode) 
    { 
     case TextMatchMode.StartsWith: 
      return "StartsWith"; 

     case TextMatchMode.EndsWith: 
       return "EndsWith"; 

     case TextMatchMode.Contains: 
      return "Contains"; 

     default: 
      return "Equals"; 
    }  
} 
+0

謝謝,阿尼!正是我在尋找的東西,像魅力一樣工作!我在lambda表達式世界中太新鮮了。 – 2011-03-27 16:28:51