Collection Sort

  • Thread starter Thread starter vzsnake
  • Start date Start date
V

vzsnake

Hello,everybody.

One my class inhereted from System.Collections.CollectionBase in
InnerList I add class B objects to InnerList and want to sort them by
multiple properties. I done the sorting, BUT when my classes have equal
values in property Name, and I sort the list by "name desc" or "name
asc", It sort wrong!
For example: (start list)
A
B
C

After Sort:
A
C
B

Can anyone explain why does it happen ?
Thanks.
 
Which version of the framework? v2 has a SortedList(of <type>) generic
class that you can use.

Mike Ober.
 
Is any chanse to correct this error in framework 1.1?
(e-mail address removed) пиÑал(а):
 
Here's code:

Public Function Compare(ByVal x As Object, ByVal y As Object) As
Integer Implements System.Collections.IComparer.Compare

Dim retVal As Integer = 0


For i As Integer = 0 To Me._props.Length - 1
If (retVal = 0) Then
Dim sortStr As String()
sortStr = Regex.Replace(_props(i).Trim(), "\s{1,}",
" ").Trim.Split(" ".ToCharArray())

Dim orderAsc As Boolean = True
If (sortStr.Length > 1) Then
orderAsc = GetOrderType(sortStr(1))
End If
Dim field As String = sortStr(0)


Dim prop As PropertyInfo =
x.GetType().GetProperty(field.Trim(), BindingFlags.IgnoreCase Or
BindingFlags.GetProperty Or BindingFlags.Public Or
BindingFlags.Instance)

Dim valx As Object = prop.GetValue(x, Nothing)
Dim valy As Object = prop.GetValue(y, Nothing)


' If (CType(valx, String) <> CType(valy, String))
Then
If (orderAsc) Then
retVal = CType(valx,
String).Trim().CompareTo(CType(valy, String).Trim())
Else
retVal = CType(valy,
String).Trim().CompareTo(CType(valx, String).Trim())
End If
' End If

End If


Next

Return retVal
End Function
 
I tested your code and it seem to work just fine in both 1.1 and 2.0. Since
you didn't include the code for _props and GetOrderType I implemented them
like this:

Private _props() As String = New String() {"name desc"}

Private Function GetOrderType(ByVal value As String) As Boolean
If value = "asc" Then
Return True
Else
Return False
End If
End Function

Then I created a small class with a name property and added a bunch of them
to an ArrayList (which is what the InnerList property returns) and called
sort with your Compare method. Worked just fine.

/claes
 
Big Thanks, Claes Bergefall for your help

But I still had to rewrite my sorting using my own stable sorting - I
used MergeSort.
 
Back
Top