1

BindingList(Of T)を拡張するクラスでLINQ式を使用して複数列のフィルタリングを実装しようとしています。関連するコードは次のとおりです。

Public Function GetFilterPredicate() As Func(Of T, Boolean)
    Dim expressionList As List(Of Expression) = New List(Of Expression)

    For Each item as FilterInfo in _FilterList
        Dim fieldName As String = item.FieldName
        Dim fieldOperator As String = item.FieldOp
        Dim fieldValue As Object = item.FieldValue

        Dim obj As ParameterExpression = Expression.Parameter(GetType(T), "obj")
        Dim objProp As MemberExpression = Expression.PropertyOrField(obj, fieldName)
        Dim filterValue As ConstantExpression = Expression.Constant(fieldValue, objProp.Type)

        Dim methodName As String = If(fieldOperator = "=", "Equal", "NotEqual")

        Dim comparisonExp As MethodCallExpression = Expression.Call( _
            GetType(Expression),
            methodName,
            New Type() {objProp.Type, filterValue.Type},
            objProp, filterValue)

        expressionList.Add(comparisonExp)
    Next

    //
    // combine the expressions in expressionList using Expression.AndAlso
    //
    // create lambda
    //

    Dim fn As Func(Of T, Boolean) = lambda.Compile

    Return fn
End Function

これは、次のように使用することを目的としています。

Dim source As IQueryable(Of T) = MyBase.Items.ToList.AsQueryable

MyBase.ClearItems()

Dim filterPredicate As Func(Of T, Boolean) = GetFilterPredicate()

For Each item As T In source.Where(filterPredicate)
    MyBase.Items.Add(item)
Next

ただし、Expression.Callステートメントで例外がスローされます。私は提供する正しい議論を完全に理解することはできません。現在のように、コードを実行すると次のエラーが発生します。

InvalidOperationException was unhandled:

No generic method 'Equal' on type 'System.Linq.Expressions.Expression' is
compatible with the supplied type arguments and arguments. No type arguments
should be provided if the method is non-generic.

どんな助けでもありがたいです、ありがとう。

4

1 に答える 1

0

リフレクションを使用して "Equal" または "NotEqual" を呼び出そうとするのではなく、単に別の式ツリーを生成する必要があります。私の貧しい VB.NET 構文を許してください。

    Dim comparisonExp As Expression = 
        If(fieldOperator = "=",
           Expression.Equal(objProp, filterValue), _
           Expression.NotEqual(objProp, filterValue))
于 2011-05-03T18:36:39.167 に答える