ArrayList.Sort in Inherited Classes

samsmithnz

Well-known member
Joined
Jul 22, 2003
Messages
1,038
Location
Boston
I have a class (clsItem), that I use to inherit in all my other classes. It looks like this (very straight forward):
Code:
Public Class clsItem

    Implements IComparer

    Private intItemKey As Integer
    Private strName As String
    Private lngBuyPrice As Long

    Overridable Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
        Compare = x.ItemKey < y.ItemKey
    End Function

    Public Property ItemKey() As Integer
        Get
            ItemKey = intItemKey
        End Get
        Set(ByVal Value As Integer)
            intItemKey = Value
        End Set
    End Property

    Public Property Name() As String
        Get
            Name = strName
        End Get
        Set(ByVal Value As String)
            strName = Value
        End Set
    End Property

    Public Property BuyPrice() As Long
        Get
            BuyPrice = lngBuyPrice
        End Get
        Set(ByVal Value As Long)
            lngBuyPrice = Value
        End Set
    End Property

End Class

I have about 10 other classes that inherit this clsItem. I then read from a database and load each type of item into the right class, then each object is loaded into an arraylist. Im now trying to sort the collection on the ItemKey field (inherited from clsItem).

Unfortunetly this isnt working out. I get this error:
Code:
System.InvalidOperationException: Specified IComparer threw an exception. ---> System.ArgumentException: At least one object must implement IComparable.
   at System.Collections.Comparer.Compare(Object a, Object b)
   at System.SorterObjectArray.QuickSort(Int32 left, Int32 right)
   --- End of inner exception stack trace ---
   at System.SorterObjectArray.QuickSort(Int32 left, Int32 right)
   at System.Array.Sort(Array keys, Array items, Int32 index, Int32 length, IComparer comparer)
   at System.Array.Sort(Array array, Int32 index, Int32 length, IComparer comparer)
   at System.Collections.ArrayList.Sort(Int32 index, Int32 count, IComparer comparer)
   at System.Collections.ArrayList.Sort()
   at XClone.modDataAccess.LoadUFOPedia(XmlDocument objXMLDoc) in C:\Projects\Xclone\modDataAccess.vb:line 121

What do I have to do to get this to work? I thought that implementing my overidden compare function in the clsItem would be enough, but this error message seems to be saying otherwise?

any ideas brainy-acs???
 
insteam of implementing IComparer try using IComparable, delete the implements statement and your Compare function and paste this in its place and see if it works.

Code:
	Implements IComparable

	Public Function CompareTo1(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
		Dim x As clsItem = DirectCast(obj, clsItem)

		If ItemKey > x.ItemKey Then Return 1
		If ItemKey < x.ItemKey Then Return -1
		Return 0
	End Function
 
Back
Top