StrataFrame Forum

Custom sort algorithm

http://forum.strataframe.net/Topic16116.aspx

By Chan - 5/3/2008

Hi,

I have item as below:





ItemName BeforeItem AfterItem

------------------------------------------

"First"

"Second"

"Third"

"B4Second" "Second"

"BetweenSecond" "Second" "B4Second"







I would like to implement IComparable to sort them so that it could be as below:



First

B4Second

BetweenSecond

Second

Third



Please advice



Thank you
By Trent L. Taylor - 5/5/2008

Here is a quick sample of how to create a collection and the sort the collection with an IComparer class.  This should get you going in the right direction:

''' <summary>
''' Create a generic collection that houses the MyItem class in a collection
''' </summary>
''' <remarks></remarks>
Public Class MyCollection
    Inherits System.Collections.CollectionBase

    Public Sub Add(ByVal item As MyItem)
        InnerList.Add(item)
    End Sub

    ''' <summary>
    ''' Use the IComparer class that we created to sort the list
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Sort()
        Dim sorter As New MySort()
        InnerList.Sort(sorter)
    End Sub
End Class

''' <summary>
''' Create the sorter to accept a MyItem class and then sort on the MyValue within the class
''' </summary>
''' <remarks></remarks>
Public Class MySort
    Implements System.Collections.IComparer

    ''' <summary>
    ''' Compare the two MyValue strings.  If you want to produce a descending sort, then reverse the x and y values.
    ''' </summary>
    ''' <param name="x"></param>
    ''' <param name="y"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
        Return String.Compare(DirectCast(x, MyItem).MyValue, DirectCast(y, MyItem).MyValue)
    End Function

End Class

Public Class MyTest

Private _Items As New MyCollection()

Private Sub TestSort()
    _Items.Add(New MyItem("Orange"))
    _Items.Add(New MyItem("Apple"))
    _Items.Add(New MyItem("Pear"))
    _Items.Add(New MyItem("Grapes"))
    _Items.Add(New MyItem("Banana"))

    '-- Sort the collection
    _Items.Sort()

End Sub

End Class