2009-06-05 7 views
14

フィルタリング可能なBindingList from this sourceを作成しました。それは素晴らしいです:LikeのようにSystem.Linq.Expressions.Expressionを作成する方法?

list.Filter("Customer == 'Name'"); 

何をすべきですか?内部はパーサのように動作し、式==または!=System.Linq.Expressions.Expressionに変換します。この場合、==System.Linq.Expressions.Expression.Equalとなります。

残念ながらSystem.Linq.Expressions.Expressionには類似の演算子が含まれていません。これを解決する方法はわかりません。

初期のコードは次のようになります。

private static Dictionary<String, Func<Expression, Expression, Expression>> 
    binaryOpFactory = new Dictionary<String, Func<Expression, Expression, Expression>>(); 

static Init() { 
    binaryOpFactory.Add("==", Expression.Equal); 
    binaryOpFactory.Add(">", Expression.GreaterThan); 
    binaryOpFactory.Add("<", Expression.LessThan); 
    binaryOpFactory.Add(">=", Expression.GreaterThanOrEqual); 
    binaryOpFactory.Add("<=", Expression.LessThanOrEqual); 
    binaryOpFactory.Add("!=", Expression.NotEqual); 
    binaryOpFactory.Add("&&", Expression.And); 
    binaryOpFactory.Add("||", Expression.Or); 
} 

その後、私は私がやりたいだろう式を作成しました:

private static System.Linq.Expressions.Expression<Func<String, String, bool>> 
    Like_Lambda = (item, search) => item.ToLower().Contains(search.ToLower()); 

private static Func<String, String, bool> Like = Like_Lambda.Compile(); 

例えば

Console.WriteLine(like("McDonalds", "donAld")); // true 
Console.WriteLine(like("McDonalds", "King")); // false 

しかしbinaryOpFactoryがこれを必要とします。

System.Linq.Expressions.Expression.Or; 

誰がどのように私の表現に変換するために教えてもらえます:

Func<Expression, Expression, Expression> 

事前に定義された式は、まさにそのように見えますか?以下のような

+0

そして、どのようにあなたのLIKEが動作しませんか?私はあなたが式を構築するのを手助けすることができますが、私はそれが最初に動作するようにする方法を理解する必要があります...正規表現?含まれますか?等? –

+0

それは問題ではありません。最終的な実装は、正規表現で行うことができます。基本的に私はFunc を持って2つのStringを渡し、returnvalueとしてtrueまたはfalseを取得します。 私の問題は、Func (binaryOpFactoryのジェネリック型のargementsを見てください)のように見えるSystem.Linq.Expressions.Expression Namespaceのオブジェクトの実装を理解できないためです私自身の比較。 –

+0

Re comment:Expression APIを理解することができます。私はブログでいくつかの基本をカバーしようとしています。 Jonの本(C#in Depth)もまた高いレベルの概要を提供します。 –

答えて

15

何か:Func<Expression,Expression,Expression>の面では

static IEnumerable<T> WhereLike<T>(
     this IEnumerable<T> data, 
     string propertyOrFieldName, 
     string value) 
{ 
    var param = Expression.Parameter(typeof(T), "x"); 
    var body = Expression.Call(
     typeof(Program).GetMethod("Like", 
      BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public), 
      Expression.PropertyOrField(param, propertyOrFieldName), 
      Expression.Constant(value, typeof(string))); 
    var lambda = Expression.Lambda<Func<T, bool>>(body, param); 
    return data.Where(lambda.Compile()); 
} 
static bool Like(string a, string b) { 
    return a.Contains(b); // just for illustration 
} 

static Expression Like(Expression lhs, Expression rhs) 
{ 
    return Expression.Call(
     typeof(Program).GetMethod("Like", 
      BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public) 
      ,lhs,rhs); 
} 
+0

素敵に見​​えるが、私はsthが必要です。 Func <式、式、式>を返します。ただし、このコンテキストではexpression1、expression2、およびexpression3は何ですか? Expression.Equalが内部的にどのように動作するかの一例は素晴らしいものです。 –

+0

私は、コードの背後にある魔法全体を理解することはできませんが、コードの第2の部分は魅力のように機能することは認めなければなりません。 –

+0

@MarcこれはLINQ to Entitiesで動作しますか? –

3

私は2つの拡張メソッドIEnumerableIQueryableためWhereFilter()を作成しました。 このようにして、このフィルタをたとえばエンティティフレームワークとは、サーバー上で実行されるフィルタリングです。

私は(?ありません)*に基づいてフィルタを使用するので、私は、下層のLINQメソッドStartsWith()EndsWith()Contains()を使用することができます。対応フォーマット:*、* A、*、*のB

使用方法:クラスの

ここ
var filtered = list.WhereFilter(i => i.Name, "a*", "First Name"); 

基礎:

/// <summary> 
/// Extension Methods for Filtering on IQueryable and IEnumerable 
/// </summary> 
internal static class WhereFilterExtensions 
{ 
    /// <summary> 
    /// Filters a sequence of values based on a filter with asterix characters: A*, *A, *A*, A*B 
    /// </summary> 
    /// <param name="source"></param> 
    /// <param name="selector">Field to use for filtering. (E.g: item => item.Name)</param> 
    /// <param name="filter">Filter: A*, *A, *A*, A*B</param> 
    /// <param name="fieldName">Optional description of filter field used in error messages</param> 
    /// <returns>Filtered source</returns> 
    public static IEnumerable<T> WhereFilter<T>(this IEnumerable<T> source, Func<T, string> selector, string filter, string fieldName) 
    { 

     if (filter == null) 
      return source; 

     if (selector == null) 
      return source; 

     int astrixCount = filter.Count(c => c.Equals('*')); 
     if (astrixCount > 2) 
      throw new ApplicationException(string.Format("Invalid filter used{0}. '*' can maximum occur 2 times.", fieldName == null ? "" : " for '" + fieldName + "'")); 

     if (filter.Contains("?")) 
      throw new ApplicationException(string.Format("Invalid filter used{0}. '?' is not supported, only '*' is supported.", fieldName == null ? "" : " for '" + fieldName + "'")); 


     // *XX* 
     if (astrixCount == 2 && filter.Length > 2 && filter.StartsWith("*") && filter.EndsWith("*")) 
     { 
      filter = filter.Replace("*", ""); 
      return source.Where(item => selector.Invoke(item).Contains(filter)); 
     } 

     // *XX 
     if (astrixCount == 1 && filter.Length > 1 && filter.StartsWith("*")) 
     { 
      filter = filter.Replace("*", ""); 
      return source.Where(item => selector.Invoke(item).EndsWith(filter)); 
     } 

     // XX* 
     if (astrixCount == 1 && filter.Length > 1 && filter.EndsWith("*")) 
     { 
      filter = filter.Replace("*", ""); 
      return source.Where(item => selector.Invoke(item).StartsWith(filter)); 
     } 

     // X*X 
     if (astrixCount == 1 && filter.Length > 2 && !filter.StartsWith("*") && !filter.EndsWith("*")) 
     { 
      string startsWith = filter.Substring(0, filter.IndexOf('*')); 
      string endsWith = filter.Substring(filter.IndexOf('*') + 1); 

      return source.Where(item => selector.Invoke(item).StartsWith(startsWith) && selector.Invoke(item).EndsWith(endsWith)); 
     } 

     // XX 
     if (astrixCount == 0 && filter.Length > 0) 
     { 
      return source.Where(item => selector.Invoke(item).Equals(filter)); 
     } 

     // * 
     if (astrixCount == 1 && filter.Length == 1) 
      return source; 

     // Invalid Filter 
     if (astrixCount > 0)    
      throw new ApplicationException(string.Format("Invalid filter used{0}.", fieldName == null ? "" : " for '" + fieldName + "'")); 

     // Empty string: all results 
     return source; 


    } 

    /// <summary> 
    /// Filters a sequence of values based on a filter with asterix characters: A*, *A, *A*, A*B 
    /// </summary> 
    /// <param name="source"></param> 
    /// <param name="selector">Field to use for filtering. (E.g: item => item.Name)  </param> 
    /// <param name="filter">Filter: A*, *A, *A*, A*B</param> 
    /// <param name="fieldName">Optional description of filter field used in error messages</param> 
    /// <returns>Filtered source</returns> 
    public static IQueryable<T> WhereFilter<T>(this IQueryable<T> source, Expression<Func<T, string>> selector, string filter, string fieldName) 
    { 

     if (filter == null) 
      return source; 

     if (selector == null) 
      return source; 

     int astrixCount = filter.Count(c => c.Equals('*')); 
     if (astrixCount > 2) 
      throw new ApplicationException(string.Format("Invalid filter used{0}. '*' can maximum occur 2 times.", fieldName==null?"":" for '" + fieldName + "'")); 

     if (filter.Contains("?"))    
      throw new ApplicationException(string.Format("Invalid filter used{0}. '?' is not supported, only '*' is supported.", fieldName == null ? "" : " for '" + fieldName + "'")); 

     // *XX* 
     if (astrixCount == 2 && filter.Length > 2 && filter.StartsWith("*") &&   filter.EndsWith("*")) 
     { 
      filter = filter.Replace("*", ""); 
      return source.Where(
       Expression.Lambda<Func<T, bool>>(
        Expression.Call(selector.Body, "Contains", null, Expression.Constant(filter)), 
        selector.Parameters[0] 
       ) 
      ); 
     } 

     // *XX 
     if (astrixCount == 1 && filter.Length > 1 && filter.StartsWith("*")) 
     { 
      filter = filter.Replace("*", ""); 
      return source.Where(
       Expression.Lambda<Func<T, bool>>(
        Expression.Call(selector.Body, "EndsWith", null, Expression.Constant(filter)), 
        selector.Parameters[0] 
       ) 
      ); 
     } 

     // XX* 
     if (astrixCount == 1 && filter.Length > 1 && filter.EndsWith("*")) 
     { 
      filter = filter.Replace("*", ""); 
      return source.Where(
       Expression.Lambda<Func<T, bool>>(
        Expression.Call(selector.Body, "StartsWith", null,   Expression.Constant(filter)), 
        selector.Parameters[0] 
       ) 
      ); 
     } 

     // X*X 
     if (astrixCount == 1 && filter.Length > 2 && !filter.StartsWith("*") && !filter.EndsWith("*")) 
     { 
      string startsWith = filter.Substring(0, filter.IndexOf('*')); 
      string endsWith = filter.Substring(filter.IndexOf('*') + 1); 

      return source.Where(
       Expression.Lambda<Func<T, bool>>(
        Expression.Call(selector.Body, "StartsWith", null,   Expression.Constant(startsWith)), 
        selector.Parameters[0] 
       ) 
      ).Where(
       Expression.Lambda<Func<T, bool>>(
        Expression.Call(selector.Body, "EndsWith", null,   Expression.Constant(endsWith)), 
        selector.Parameters[0] 
       ) 
      ); 
     } 

     // XX 
     if (astrixCount == 0 && filter.Length > 0) 
     { 
      return source.Where(
       Expression.Lambda<Func<T, bool>>(
        Expression.Equal(selector.Body, Expression.Constant(filter)), 
        selector.Parameters[0] 
       ) 
      ); 
     } 

     // * 
     if (astrixCount == 1 && filter.Length == 1) 
      return source; 

     // Invalid Filter 
     if (astrixCount > 0) 
      throw new ApplicationException(string.Format("Invalid filter used{0}.", fieldName == null ? "" : " for '" + fieldName + "'")); 

     // Empty string: all results 
     return source; 

    } 
} 
+0

によって ' Entity Frameworkとは、サーバー上で実行されるフィルタリングです。つまり、データベースで意味しますか?つまり、SQLに変換されますか?私は 'selector.Invoke'がEFのSQLへの変換を妨げていたという印象を受けましたか? – JoeBrockhaus

+0

はい、ExpressionTreeは 'LINQ Provider'によって変換されます。 Enity Frameworkを使用する場合、LINQ to Entitiesプロバイダは、それをデータベース上で実行されるSQL文字列に変換します。結果はArrayでなく、DataReaderを処理するIEnumerableになります。 –

関連する問題