KeyedCollection(TKey, TItem) is the abstract base class for a collection whose keys are embedded in the values.
Imports System
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Public Class SimpleOrder
Inherits KeyedCollection(Of Integer, Product)
Public Sub New()
MyBase.New()
End Sub
Protected Overrides Function GetKeyForItem( _
ByVal item As Product) As Integer
Return item.PartNumber
End Function
End Class
Public Class Demo
Public Shared Sub Main()
Dim weekly As New SimpleOrder()
weekly.Add(New Product(1, "A", 4, 4.7))
weekly.Add(New Product(2, "B", 2, 5.3))
weekly.Add(New Product(3, "C", 1, 2.5))
weekly.Add(New Product(4, "D", 1, 5.17))
Display(weekly)
Console.WriteLine(weekly.Contains(3))
Console.WriteLine(weekly(3).Description)
weekly.Remove(3)
Display(weekly)
weekly.Insert(2, New Product(5, "E", 10, .5))
Display(weekly)
Dim coweekly As Collection(Of Product) = weekly
Console.WriteLine(coweekly(2).Description)
coweekly(2) = New Product(6, "F", 27, 5.98)
Dim temp As Product = coweekly(2)
Console.WriteLine(weekly.IndexOf(temp))
weekly.Remove(temp)
Display(weekly)
weekly.RemoveAt(0)
Display(weekly)
End Sub
Private Shared Sub Display(ByVal order As SimpleOrder)
For Each item As Product In order
Console.WriteLine(item)
Next item
End Sub
End Class
Public Class Product
Public ReadOnly PartNumber As Integer
Public ReadOnly Description As String
Public ReadOnly UnitPrice As Double
Private _quantity As Integer = 0
Public Sub New(ByVal partNumber As Integer, _
ByVal description As String, _
ByVal quantity As Integer, _
ByVal unitPrice As Double)
Me.PartNumber = partNumber
Me.Description = description
Me.Quantity = quantity
Me.UnitPrice = unitPrice
End Sub 'New
Public Property Quantity() As Integer
Get
Return _quantity
End Get
Set
If value < 0 Then
Throw New ArgumentException("Quantity cannot be negative.")
End If
_quantity = value
End Set
End Property
Public Overrides Function ToString() As String
Return String.Format(Description)
End Function
End Class
Related examples in the same category