Search code examples
vb.netlistsortingvisual-studio-2005.net-2.0

Sort a list based on an item inside the list that is another list


As the titel says, but it gets even more complicated. this is some example code

class person
prop name as string
prop age as int
prop properties as List(of ExtraProps)

class ExtraProps
prop key as string
prop value as string

so say that i want to sort a list of class person based on an object ExtraProps.value where the Key = "name"

do note that i am working in vs2005 and in version 2.0 of .NET


Solution

  • First i would like to thank @TimSchmelter For this answer. this works perfectly in .NET 2.0 and in VS2005.

    Public Class TaskKeyComparer
    Implements IComparer(Of Trimble_Planning.TaskData)
    
    Private ReadOnly _keyComparison As StringComparison
    Private ReadOnly _valueComparison As StringComparison
    Private ReadOnly _key As String
    
    Public Sub New(ByVal key As String, Optional ByVal keyComparison As StringComparison = StringComparison.CurrentCulture, Optional ByVal valueComparison As StringComparison = StringComparison.CurrentCulture)
        _key = key
        _keyComparison = keyComparison
        _valueComparison = valueComparison
    End Sub
    
    Public Function Compare(ByVal x As person, ByVal y As person) As Integer Implements IComparer(Of person).Compare
        If x Is Nothing AndAlso y Is Nothing Then Return 0
        If x Is Nothing OrElse y Is Nothing Then Return CInt(IIf(x Is Nothing, -1, 1))
        If x.properties Is Nothing AndAlso y.properties Is Nothing Then Return 0
        If x.properties Is Nothing OrElse y.properties Is Nothing Then Return CInt(IIf(x.properties  Is Nothing, -1, 1))
    
        Dim xKeyValue As String = Nothing
        Dim yKeyValue As String = Nothing
        For Each prop As ExtraProps In x.properties 
            If String.Equals(prop.key, _key, _keyComparison) Then
                xKeyValue = prop.value
                Exit For
            End If
        Next
        For Each prop As ExtraProps In y.properties 
            If String.Equals(prop.key, _key, _keyComparison) Then
                yKeyValue = prop.value
                Exit For
            End If
        Next
        Return String.Compare(xKeyValue, yKeyValue, _valueComparison)
    End Function
    End Class
    

    then use it like this

    personList.Sort(New TaskKeyComparer("name"))