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

I often have a specific class, and I also define another class, which is just a collection of another class. For this, it was easiest for me to define another class as Inherits List (Of Type). The reason I define the collection class is to add extra features 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 refer to Car by name or index, then how .NET seems to make collections. Take for example the .NET ToolStripItemCollection. You can reference elements inside it in one of two ways: MyCollection (2) MyCollection ("MyItemName")

Of course, my question is how can I define my own collection so that I can reference it by index or name. Now I can only refer to the index.

+4
source share
5 answers

You can use 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 
+6
source

You can overload the element:

 '''<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 
+2
source

You can try to inherit from System.Collections.Generic.Dictionary instead of a list, and when adding - also set the key.

+1
source

Give the SortedDictionary the look ... something like this:

 Public Class Car Property Name As String End Class Public Class CarCollection Inherits SortedDictionary(Of String, Car) 'Extend, override as needed, adding in your indexer property Public Default ReadOnly Property Item(index As Integer) As Car Get Return Me.Values.ElementAt(index) End Get End Property End Class 

Then you can use it as follows:

 Dim collection As New CarCollection() collection.Add("YourNameHere", New Car()) collection("YourNameHere") 
+1
source

The System.Collections.Generic.SortedList collection allows you to access elements by index (through the Keys and Values properties) and a key.

0
source

All Articles