Implementing string comparer in custom Linq Provider in VB

拜拜、爱过 提交于 2019-12-06 12:34:11

Use the following class:

Imports System.Linq.Expressions

Public Class VbCompareReplacer
    Inherits ExpressionVisitor

    Public Overrides Function Visit(node As Expression) As Expression
        If Not TypeOf node Is BinaryExpression Then Return MyBase.Visit(node)

        Dim binaryExpression = DirectCast(node, BinaryExpression)

        If Not TypeOf binaryExpression.Left Is MethodCallExpression Then Return MyBase.Visit(node)

        Dim method = DirectCast(binaryExpression.Left, MethodCallExpression)

        If Not (method.Method.DeclaringType = GetType(Microsoft.VisualBasic.CompilerServices.Operators) AndAlso
            method.Method.Name = "CompareString") Then Return MyBase.Visit(node)

        Dim left = method.Arguments(0)
        Dim right = method.Arguments(1)

        Return If(binaryExpression.NodeType = ExpressionType.Equal,
                  Expression.Equal(left, right),
                  Expression.NotEqual(left, right))
    End Function
End Class

Now if you have an expression from the vb compiler, for example

Dim expressionFromVb As Expression(Of Func(Of String, Boolean)) = Function(x) x = "b"

which has the structure {(CompareString(x, "b", False) == 0)} use

Dim newExpression = New VbCompareReplacer().Visit(expressionFromVb)

instead of expressionFromVb which has the structure {x => (x == "b")}. All messy vb comparisons are replaced by the expected (in-)equality comparisons. If you put newExpression into your linq provider written for c#, it should work properly now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!