views:

54

answers:

1

I have a function which creates a different type of expression depending on the value of the variable 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.

+1  A: 

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
jeroenh