Sorting a collection in VB

B

BSnow

I have a collection that inherits from NameObjectCollectionBase. Does anyone
know how to sort this type of collection.

I have tried the following code, but to no avail.

In my collection I have the following method.

Public Sub Sort()
Array.Sort(MyBase.BaseGetAllKeys, MyBase.BaseGetAllValues)
End Sub


In my object which populates the collection I have the following method.

Overridable Function CompareTo(ByVal obj As Object) As Integer Implements
IComparable.CompareTo
Return Name.ToString.CompareTo(CType(obj, R60Amount).Name)
End Function

Obviously it is not that simple.
 
M

Michael Giagnocavo [MVP]

Well, you could write your own sorter, or array sort the GetAllKeys, then
move the values around based on that.

What are you trying to accomplish by sorting it?

-mike
MVP
 
B

BSnow

I finally got it to work. The sort method does work, but the BaseGetAllKeys
and BaseGetAllValues method pass their arrays byval and not byref so the
underlying array does not get sorted. I had to create my own arrays and
populate them with the underlying arrays, sort them, clear the collection
and then repopulate with the sorted arrays. My collections are fairly small
so the speed is not even noticeable.

This may not be the best way to handle this, but it works for now.

The reason I needed to sort the collections is that when I for each through
them I needed the objects returned sorted.

This is the code for my sort command.

Public Sub Sort()

If Not _Sorted Then

Dim Index(Me.Count - 1) As String
Dim Values(Me.Count - 1) As R60Row

MyBase.BaseGetAllKeys.CopyTo(Index, 0)
MyBase.BaseGetAllValues.CopyTo(Values, 0)

Array.Sort(Index, Values)

MyBase.BaseClear()

For i As Integer = 0 To Index.Length - 1

MyBase.BaseAdd(Index(i), Values(i))

Next

_Sorted = True

End If

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top