I often have a class defined and I also define another class that is simply a collection of the other class. To do this I found it easiest just to define the other class as Inherits List(Of Type). The reason I define a collection class is to add extra functionality to the collection. Take the following code for example.
Class Car
Property Name As String
Property Year As Short
Property Model As String
End Class
Class CarCollection
Inherits List(Of Car)
Overloads Sub Add(ByVal Name As String, ByVal Year As Short, ByVal Model As String)
Dim c As New Car
c.Name = Name
c.Year = Year
c.Model = Model
Add(c)
End Sub
End Class
Now if I declare a CarCollection variable, how can I reference the Car by either name or the index value, the way that .NET seems to do collections. Take for instance the .NET ToolStripItemCollection. You can reference items within it either of these two ways: MyCollection(2) MyCollection("MyItemName")
My quesion of course is how can I define my own collection so that I can reference it by index or name like that. Right now I can only reference it by index.
You can use a KeyedCollection
:
Imports System.Collections.ObjectModel
Public Class CarCollection
Inherits KeyedCollection(Of String, Car)
Protected Overrides Function GetKeyForItem(ByVal item As Car) As String
Return item.Name
End Function
End Class
You can overload Item:
'''<summary>
'''Gets or sets a Car object by name.
'''</summary>
Public Default Property Item(ByVal name As String) As Car
Get
'Return the Car with the specified name
End Get
Set(ByVal value As Car)
'Set the Car with the specified name
End Set
End Property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With