根据列表中另一个列表中的项目对列表进行排序

问题描述 投票:0回答:2

正如标题所说,但它变得更加复杂。这是一些示例代码

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

所以说我想基于对象ExtraProps.value对类人物列表进行排序,其中Key =“name”

请注意我在vs2005和.NET 2.0版本中工作

vb.net list sorting visual-studio-2005 .net-2.0
2个回答
0
投票

EG

Private Function ComparePersonsByExtraPropsName(p1 As Person, p2 As Person) As Integer
    Return GetFirstExtraProp(p1.Properties, "Name").Value.CompareTo(GetFirstExtraProp(p2.Properties, "Name").Value)
End Function

Private Function GetFirstExtraProp(properties As IEnumerable(Of ExtraProps), key As String) As ExtraProps
    For Each ep As ExtraProps In properties
        If ep.Key = key Then
            Return ep
        End If
    Next

    Return Nothing
End Function

然后:

Dim personList As New List(Of Person)

'...

personList.Sort(AddressOf ComparePersonsByExtraPropsName)

0
投票

首先,我要感谢@TimSchmelter对于这个答案。这在.NET 2.0和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

然后像这样使用它

personList.Sort(New TaskKeyComparer("name"))
© www.soinside.com 2019 - 2024. All rights reserved.