Store Object in Most Recent Used Item List
Imports System
Imports System.Windows.Forms
Imports System.Collections.Generic
Imports System.ComponentModel
Public Class MainClass
Shared Sub Main()
Dim the_items As New MostRecentList(Of DataItem)(4)
Dim new_data As New DataItem
new_data.Text = "A"
the_items.Add(new_data)
new_data = new DataItem
new_data.Text = "B"
the_items.Add(new_data)
For i As Integer = 0 To the_items.Count - 1
Console.WriteLine(the_items.Item(i).Text)
Next i
End Sub
End Class
Public Class MostRecentList(Of ItemType As IComparable)
' Initialize MaxItems for the new list.
Public Sub New(ByVal max_items As Integer)
MaxItems = max_items
End Sub
' The Item property.
Private m_Items As New List(Of ItemType)
<Description("The items."), _
Category("Data")> _
Public Property Item(ByVal index As Integer) As ItemType
Get
Return m_Items(index)
End Get
Set(ByVal value As ItemType)
m_Items(index) = value
End Set
End Property
' The MaxItems property.
Private m_MaxItems As Integer = 4
<Description("The maximum number of items in the list."), _
Category("Data")> _
Public Property MaxItems() As Integer
Get
Return m_MaxItems
End Get
Set(ByVal value As Integer)
m_MaxItems = value
' Resize appropriately.
Do While m_Items.Count > m_MaxItems
m_Items.RemoveAt(m_Items.Count - 1)
Loop
End Set
End Property
' The current number of items.
<Description("The current number of items."), _
Category("Data")> _
Public ReadOnly Property Count() As Integer
Get
Return m_Items.Count
End Get
End Property
' Add an item to the top of the list.
Public Sub Add(ByVal value As ItemType)
' Remove the item if it is present.
Remove(value)
' Add the item to the top of the list.
m_Items.Insert(0, value)
' Make sure there are at most MaxItems items.
If m_Items.Count > m_MaxItems Then m_Items.RemoveAt(m_Items.Count - 1)
End Sub
' Remove an item.
Public Sub Remove(ByVal value As ItemType)
' Find the item.
For i As Integer = m_Items.Count - 1 To 0 Step -1
If value.CompareTo(m_Items(i)) = 0 Then
m_Items.RemoveAt(i)
End If
Next i
End Sub
' Remove an item at a specific position.
Public Sub RemoveAt(ByVal index As Integer)
m_Items.RemoveAt(index)
End Sub
End Class
Public Class DataItem
Implements IComparable
Public Text As String
Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
Dim data_item As DataItem = DirectCast(obj, DataItem)
Return String.Compare(Me.Text, data_item.Text)
End Function
End Class
Related examples in the same category