View Single Post
  #5 (permalink)  
Old March 30th, 2009, 03:45 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
Default

Here we go, this compiled for me:
vbnet 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 Func(Of T, Object))

        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().OrderBy(Of Object)(sortExpression).ToList()
        Else
            Return Me.AsQueryable().OrderByDescending(Of Object)(sortExpression).ToList()
        End If
    End Function

List(Of T) already knows about typeparam T (obviously) so the AsQueryable, OrderBy etc extension methods don't need it to be specified.

Phil
The Following User Says Thank You to philip_cole For This Useful Post:
realkewl (March 30th, 2009)