I have a method for Linq when attempting to sort by a dynamic property

  • Thread starter Thread starter sqlguy
  • Start date Start date
S

sqlguy

Guest
As in the Title I have the following two sets of code. The first is for a generic method to get the property value for a named property and the second for a Linq statement that uses it to sort depending on the value of a certain property.

Generic Method:

Public Function GetPropertyValue(theObject As Object, thePropertyName As String) As Object
Dim objectProperty As PropertyInfo = theObject.GetType().GetProperty(thePropertyName)
If objectProperty Is Nothing Then
Dim woops As Integer = 1
End If

Dim retVal As Object = objectProperty.GetValue(theObject)
Dim stp As Integer = 1
Return retVal
End Function


The Linq usage:

If GroupSortProperty = String.Empty Then
ret = (From dp As DraftPlayer In fullDraftPlayers Where dp.draftedByTeamId = VMSelectedTeam.id Order By dp.draftYear Descending, dp.overallPickNumber Ascending).ToList()
Else
ret = (From dp As DraftPlayer In fullDraftPlayers Where dp.draftedByTeamId = VMSelectedTeam.id Order By GetPropertyValue(dp, GroupSortProperty), dp.draftYear Descending, dp.overallPickNumber Ascending).ToList()
End If


The above linq code will sort on a property if a GroupSortProperty (the name of the property) is set.

Just wondering if anyone can see a problem with this approach.



Lloyd Sheen

Continue reading...
 
Back
Top