Hello,
\n
\nI have a lists of different custom classes and each must be sorted severals times before the algorithm is complete. For each sort I wrote a comparer. Sofar so good. Everything works.
\nBut:
\nBy now I have about a dozen different comparers in more than one class and it is still getting more. I wonder if there is a way to limit the number by writing a new general function that can be used to sort all lists without the need for a specific comparer.
\n
\nBelow is what I\'ve got so far. But it does not work.
\n
\n"System.Collections.Generic.List(Of ClassA)" can not be converted into "System.Collections.Generic.List(Of Object)."
\n
\nWhat am I doing wrong?
\nAny help would be appreciated.
\n
\n
\r\n
Code:
\r\n
Public Class SortList\n\n Private _fields() As String\n Private _sort() As Integer\n\n Public Sub Sort(ByRef list As List(Of Object), ByVal SortFields() As String)\n\n ReDim _fields(SortFields.Length - 1)\n ReDim _sort(SortFields.Length - 1)\n\n For i As Integer = 0 To SortFields.Length - 1\n\n Dim temp() As String = SortFields(i).Split(" ")\n\n _fields(i) = temp(0)\n If temp.Length > 1 Then\n Select Case temp(1).ToLower().Trim()\n Case "", "asc"\n _sort(i) = 1\n Case "desc"\n _sort(i) = -1\n End Select\n Else\n _sort(i) = 1\n End If\n\n Next i\n\n Select Case SortFields.Length\n\n Case 1\n list.Sort(AddressOf Compare1)\n \'Case 2\n \' list.Sort(AddressOf Compare2)\n \'Case 3\n \' list.Sort(AddressOf Compare3)\n \'Case 4\n \' list.Sort(AddressOf Compare4)\n \'Case 5\n \' list.Sort(AddressOf Compare5)\n End Select\n\n End Sub\n\n Private Function Compare1(x As Object, y As Object) As Integer\n\n If x Is Nothing Then\n If y Is Nothing Then\n Return 0\n Else\n Return _sort(0) * -1\n End If\n Else\n If y Is Nothing Then\n Return _sort(0) * 1\n Else\n Return _sort(0) * x.GetType().GetProperty(_fields(0)).GetValue(x, Nothing).CompareTo(y.GetType().GetProperty(_fields(0)).GetValue(y, Nothing))\n End If\n End If\n\n End Function\n\nEnd Class\n\nSub CalcSomething\n\n Dim ListA As New List(Of ClassA)\n Dim ListB As New List(Of ClassB)\n\n Dim sl As New SortList()\n sl.Sort(ListA, {"Field1" desc, "Field2"})\n sl.Sort(ListB, {"FieldX desc"})\n\nEnd Sub\r\n
\r\n \r\n\r\n