在DictionaryBase集合上排序

时间:2014-04-02 05:16:09

标签: vb.net

我对如何在自定义DictionaryBase集合上实现排序感到困惑。示例代码如下:

Public Class CarCollection

Inherits DictionaryBase

Public ReadOnly Property Values() As Car()
    Get
        Dim aRet(Dictionary.Count - 1) As Car
        Dictionary.Values.CopyTo(aRet, 0)
        Return aRet
    End Get
End Property

Public Sub New()

End Sub

Public Sub Add(ByVal c As Car)
    If Not Dictionary.Contains(c.Make) Then
        SyncLock Dictionary
            Dictionary.Add(c.Make, c)
        End SyncLock
    Else
        SyncLock Dictionary
            Dictionary(c.Make) = c
        End SyncLock
    End If
End Sub

Public Overrides Function ToString() As String
    Try
        Dim sTxt As String = String.Empty
        Dim aCars() As Car = Values
        For i As Int32 = 0 To aCars.Length - 1
            sTxt &= aCars(i).Make & ", Yr: " & aCars(i).Year & ", Price: " & aCars(i).Price & vbCrLf
        Next
        Return sTxt
    Catch ex As Exception
        Return String.Empty
    End Try
End Function

Public Overloads Sub Sort()

End Sub
End Class

Public Class Car
Implements IComparable(Of Car)
Private m_Make As String
Private m_Year As Int32
Private m_Price As Double
Public ReadOnly Property Make() As String
    Get
        Return m_Make
    End Get
End Property
Public ReadOnly Property Year() As String
    Get
        Return m_Year
    End Get
End Property
Public ReadOnly Property Price() As String
    Get
        Return m_Price
    End Get
End Property

Public Sub New(ByVal sMake As String, ByVal iYear As Int32, ByVal dPrice As Double)
    m_Make = sMake : m_Year = iYear : m_Price = dPrice
End Sub

Public Function CompareTo(ByVal other As Car) As Integer Implements System.IComparable(Of Car).CompareTo
    Select Case m_Year
        Case Is > other.Year : Return 1
        Case Is < other.Year : Return -1
        Case Else
            Select Case m_Price
                Case Is > other.Price : Return 1
                Case Is < other.Price : Return -1
                Case Else : Return 0
            End Select
    End Select
End Function
End Class

Public Class Form1
Private m_Makes() As String
Private m_Cars As New CarCollection
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    m_Makes = New String() {"Aston Martin", "Audi", "Bentley", "BMW", "Caterham", "Chrysler", "Citeron", "Dodge", "Ferari" _
                 , "Fiat", "Ford", "Honda", "Hyundai", "Jaguar", "Lexus", "Mazda", "Skoda", "Suzuki", "Volvo", "Toyota"}

    'Randomly add car
    For n as int32 = 0 to 9
        Dim i As Int32 = Rnd() * 20
        Dim y As Int32 = Rnd() * 5 + 2008
        Dim p As Double = Rnd() * 500000

        m_Cars.Add(New Car(m_Makes(i), y, p))
    Next 'n
    'How do I get the sorted Dictionary here?
    Debug.Print(m_Cars.ToString)
End Sub
End Class

如何对集合进行排序?或者有没有其他方法来实现类似的功能?

  • 斯利拉姆

1 个答案:

答案 0 :(得分:1)

你可以选择SortedDictionary。或者只使用元组列表并使用LINQ的OrderBy方法进行相应排序。