Search code examples
vb.netsortingsortedset

Custom sort of a SortedSet in VB.Net


I have a sortedSet with following data:

aga12
aga44
dp1
dp11
reg13
reg45
sat5
sat6

I would like this list to be sorted aphabetically but I want the dp values to be on top so like this:

dp1
dp11
aga12
aga44
reg13
reg45
...

Anyone know how I can custom sort this SortedSet. I am using VB.NET

thanks


Solution

  • You could sort using a custom compare class

      Dim myList As New List(Of String)
      .... 
      myList.Sort(New DpCompare)
    

    And

      Private Class DpCompare
            Implements IComparer(Of String)
    
    
            Public Function Compare(ByVal x As String, ByVal y As String) As Integer Implements System.Collections.Generic.IComparer(Of String).Compare
    
                Dim isDPx As Boolean = x.StartsWith("dp")
                Dim isDPy As Boolean = y.StartsWith("dp")
    
                If isDPx AndAlso isDPy = False Then
                    Return -1
                End If
    
                If isDPy AndAlso isDPx = False Then
                    Return 1
                End If
    
                Return String.Compare(x, y)
    
            End Function
        End Class