View Single Post
  #2 (permalink)  
Old March 29th, 2009, 11:41 AM
philip_cole philip_cole is offline
Friend of Wrox
Points: 894, Level: 11
Points: 894, Level: 11 Points: 894, Level: 11 Points: 894, Level: 11
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
Join Date: Sep 2005
Location: London, , United Kingdom.
Posts: 166
Thanks: 2
Thanked 33 Times in 33 Posts

Hi realkewl,

Your'e not far off. Try this:

vb Code:
Public Function SortByPropertyName(ByVal propertyName As String, ByVal ascending As Boolean) As List(Of T)
    'Create a Lambda expression to dynamically sort the data.
    Dim param As ParameterExpression
    Dim body As Expression
    Dim sortExpression As Expression(Of T)

    param = Expression.Parameter(GetType(T), "N")
    body = Expression.Convert(Expression.Property(param, propertyName), GetType(Object))
    sortExpression = Expression.Lambda(Of Func(Of T, Object))(body, param)

    If ascending Then
        Return Me.AsQueryable(Of T)().OrderBy(Of T, Object)(sortExpression).ToList(Of T)()
        Return Me.AsQueryable(Of T)().OrderByDescending(Of T, Object)(sortExpression).ToList(Of T)()
    End If
End Function

If you ever want to convert between c# and vb, I find this site gets it right most of the time.