开发者

Use property type in expression

I have a function which creates a different type of expression depending on the value of the var开发者_开发知识库iable passed in.

Protected Function BuildSortPredicate(ByVal tableType As Object, ByRef expr As Expression)
    Dim sortExpression As Expression
    If tableType Is "Job" Then
        sortExpression = Expression.Lambda(Of Func(Of Job, String))(expr)
    ElseIf tableType Is "User" Then
        sortExpression = Expression.Lambda(Of Func(Of User, Integer))(expr)
    ...
    End If
    Return sortExpression
End Function

How can I avoid the lengthy if/else (or case switch) structure? Ideally, I'm looking for something like this:

Protected Function BuildSortPredicate(ByVal tableType As Object, ByRef exprt As Expression)
    Dim sortExpression As Expression
    sortExpression = Expression.Lambda(Of Func(Of tableType, String))(expr)
    Return sortExpression
End Function

The overall goal here is to convert the expression to the appropriate type so that I can use it in my LINQ query.


You want to make a Generic function

Protected Function BuildSortPredicate(Of T)(ByVal expr As Expression) As Expression
    Dim sortExpression As Expression
    sortExpression = Expression.Lambda(Of Func(Of T, String))(expr)
    Return sortExpression
End Function
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜