Buen dia!
Hoy tengo una pregunta con respecto a mi codigo.
El problema que esto intenta resolver es ordenar una lista por propiedades de
sus objetos por ejemplo podria tener un objeto:
persona que tiene las propiedades fechaDeNacimiento y provincia( que es un
objeto que contiene la propiedad id) entonces podria escribir
funciones.orderList(listaDePersonas,"fechaDeNaciemiento DESC","provincia.id
ASC")
donde a partir del segundo parametro se define el criterio de ordenamiento.
Queria saber si esta bien hecho o hay algo que ya lo hace y de forma optimizada.
Y si alguien se pregunta porque lo hice asi: Es una de las tantas de mi jefe!
Saludos y gracias,
Javier Wamba
Imports System
Public Class Funciones
#Region "Ordenamiento"
Private Shared mutexOrden As New Threading.Mutex
Private Shared ordenamientos() As String
Public Shared Sub orderList(ByVal list As List(Of base), ByVal ParamArray
orders() As String)
mutexOrden.WaitOne()
Try
ordenamientos = orders
list.Sort(AddressOf order)
mutexOrden.ReleaseMutex()
Catch ex As Exception
mutexOrden.ReleaseMutex()
End Try
End Sub
Private Shared Function devolverPropiedad(ByVal b1 As entidades.base, ByVal
prop() As String, ByVal index As Integer) As Object
Try
If prop.Length - 1 = index Then
Return b1.GetType.GetProperty(prop(index)).GetValue(b1, Nothing)
Else
Return devolverPropiedad(b1.GetType.GetProperty(prop(index)).GetValue(b1,
Nothing), prop, index + 1)
End If
Catch ex As Exception
Throw ex
End Try
End Function
Private Shared Function orderAuxiliar(ByVal b1 As entidades.base, ByVal b2 As
entidades.base, ByVal index As Integer) As Integer
Dim vec() As String
Try
vec = ordenamientos(index).Split(" ")
If vec.Length = 2 Then
Dim compar As Integer = devolverPropiedad(b1, vec(0).Split("."),
0).compareto(devolverPropiedad(b2, vec(0).Split("."), 0))
If compar = 0 Then
If ordenamientos.Length - 1 = index Then
Return compar
Else
Return orderAuxiliar(b1, b2, index + 1)
End If
Else
If vec(1).ToUpper = "DESC" Then
Return compar * (-1)
Else
Return compar
End If
End If
ElseIf vec.Length = 1 Then
Dim compar As Integer = devolverPropiedad(b1, vec(0).Split("."),
0).compareto(devolverPropiedad(b2, vec(0).Split("."), 0))
If compar = 0 Then
If ordenamientos.Length - 1 = index Then
Return compar
Else
Return orderAuxiliar(b1, b2, index + 1)
End If
Else
Return compar
End If
Else
Throw New Exception("Demasiados espacios")
End If
Catch ex As Exception
Throw ex
End Try
End Function
Private Shared Function order(ByVal b1 As entidades.base, ByVal b2 As
entidades.base) As Integer
Try
Return orderAuxiliar(b1, b2, 0)
Catch ex As Exception
Throw ex
End Try
End Function
#End Region
End class
Public Class base
Friend Sub New()
End Sub
End Class