Limit List (Of T) Size - VB.NET

I am trying to limit the size of my general list so that after it contains a certain number of values, it will no longer add.

I am trying to do this using the Capacity property of a List object, but this does not work.

Dim slotDates As New List(Of Date) slotDates.Capacity = 7 

How do people's advice limit the size of a list?

I am trying to avoid checking the size of the list after adding each object.

+7
list generics limit
source share
5 answers

There are several ways to add things to a List<T> : Add, AddRange, Insert, etc.

Consider a solution that inherits from Collection<T> :

 Public Class LimitedCollection(Of T) Inherits System.Collections.ObjectModel.Collection(Of T) Private _Capacity As Integer Public Property Capacity() As Integer Get Return _Capacity End Get Set(ByVal value As Integer) _Capacity = value End Set End Property Protected Overrides Sub InsertItem(ByVal index As Integer, ByVal item As T) If Me.Count = Capacity Then Dim message As String = String.Format("List cannot hold more than {0} items", Capacity) Throw New InvalidOperationException(message) End If MyBase.InsertItem(index, item) End Sub End Class 

Thus, the ability is respected regardless of whether you are Add or Insert .

+9
source share

There is no built-in way to limit the size of the list (Of T). The Capacity property simply changes the size of the buffer for the deaf, and does not limit it.

If you want to limit the size of the list, you need to create a wrapper that checks for an invalid size. for example

 Public Class RestrictedList(Of T) Private _list as New List(Of T) Private _limit as Integer Public Property Limit As Integer Get return _limit End Get Set _limit = Value End Set End Property Public Sub Add(T value) if _list.Count = _limit Then Throw New InvalidOperationException("List at limit") End If _list.Add(value) End Sub End Class 
+14
source share

You want to get a new LimitedList and obscure the add methods. Something like this will help you get started.

 public class LimitedList<T> : List<T> { private int limit; public LimitedList(int limit) { this.limit = limit; } public new void Add(T item) { if (Count < limit) base.Add(item); } } 

I just realized that you are in VB, I will transfer soon

Edit See Jared for VB Version. I will leave it here if someone wants to start with a C # version.

For what it costs has a slightly different approach, since it extends the List class, rather than encapsulating it. Which approach you want to use depends on your situation.

+5
source share

You must implement your own list / collection if you need to limit the maximum number of elements in it.

0
source share

There is no such object in the list.

material capacity is simply a performance optimization.

You will have to collapse your own class, list and redefine the Add implementation.

0
source share

All Articles