Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a collection in .NET so you can reference items either by value or name

Tags:

.net

vb.net

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.

like image 718
Jeff Stock Avatar asked Apr 18 '11 18:04

Jeff Stock


2 Answers

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
like image 54
Mark Cidade Avatar answered Oct 16 '22 01:10

Mark Cidade


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
like image 23
Ry- Avatar answered Oct 16 '22 00:10

Ry-