Download source - 30 KBDownload library - 5 KB
Introduction
This set of
Non-Repeatable Collections
has a very simple concept - to only allow one item of each type to be added, meaning that you cannot have duplicate items in the collection.
Background
Although the .NET Framework includes a
HashSet(Of T)
collection that does not allow repeated items, I figured that some developers may not want to switch to a collection such as the
HashSet
, but rather use ones that have the same functionality of common collections such as
Lists
and
Stacks
, which are specialised for certain tasks.
The idea for creating this set of 11 collections came to me while I was in the early stages of developing a music software program. I had to store musical notes in a
List
, but not allow the same note to be added twice.
Using the Code
To use the code, first add a reference to the
NonRepeatableCollections.dll library. This is located in the
Bin/Release folder.
Add these
Imports
statement as follows:
Imports NonRepeatableCollections
Imports NonRepeatableCollections.Generic
You can then use the collections as normal, for example:
Dim list As New NonRepeatableList(Of String)
list.Add("hello")
list.Add("goodbye")
list.Add("hello")
How It Works
To create the non repeatable collections, I derived from the individual collection classes, shadowing the methods that added items to the collections, for example the
Add
method of the
List(Of T)
or the
Enqueue
method of the
Queue
.
In these shadowed methods, the code performs a check on the collection to make sure that the item(s) being added are not already contained. If they are already contained, the code discards the item, otherwise it proceeds to add it to the collection.
That's basically all there is to it, I also coded shadowed methods for other less obvious methods like the
Insert
method of the
List(Of T)
, as this also adds item(s) to the collection. It performs the same check as with the
Add
method etc.
Current Collections
Here is a list of the collections currently in the library:
Normal
NonRepeatableArrayList
NonRepeatableHashtable
NonRepeatableQueue
NonRepeatableSortedList
NonRepeatableStack
Generic
NonRepeatableDictionary
NonRepeatableList
NonRepeatableQueue
NonRepeatableSortedDictionary
NonRepeatableSortedList
NonRepeatableStack