dimanche 12 novembre 2017

Sort all List properties (and subproperties) of an object

I'm trying to sort all of the List properties of an object (using OrderBy). It's a complex object that has Lists that may contain Lists. I figured that reflection and recursion would get me there, but I seem to be stumbling on actually sorting the lists.

Here is the code I have:

Private Sub SortData(ByRef obj As Object)
    Dim type As Type = obj.GetType()
    Dim properties As PropertyInfo() = type.GetProperties()

    For Each item As PropertyInfo In properties
        If Not item.PropertyType.FullName.Contains("System.Collection") AndAlso item.PropertyType.FullName.Contains("MyType") Then
            Dim value = obj.GetType().GetProperty(item.Name).GetValue(obj)
            If value IsNot Nothing Then
                SortData(value)
            End If
        End If

        If item.PropertyType.FullName.Contains("System.Collection") Then
            Dim value = obj.GetType().GetProperty(item.Name).GetValue(obj)
            If value IsNot Nothing Then
                Dim subType As Type = value(0).GetType()
                Dim subProperties As PropertyInfo() = subType.GetProperties()
                If subProperties.Any(Function(x) x.Name = "SortKey") Then
                    ' --- Struggling here! ---
                    Dim castList = TryCast(value, List(Of MoreDetail))
                    value = castList.OrderBy(Function(x) x.SortKey)
                    value = TryCast(value, List(Of MoreDetail))
                    ' --- End struggle ---
                End If

                For Each subProperty In subProperties
                    SortData(value.GetType().GetProperty(subProperty.Name).GetValue(value))
                Next
            End If
        End If
    Next

End Sub

The main problem is in the "struggling here" section of the code - I seem to have to cast the object into its original type, but that defeats the purpose of the reflection as different objects will have a different list type, so ideally I'd be able to cast the object based on its reflected type.

Thanks for the help!





Aucun commentaire:

Enregistrer un commentaire