Working with collections in the .NET Framework






3.50/5 (16 votes)
Jun 22, 2004
6 min read

74800

2
Introduction to collections in the .NET Framework.
Introduction
In this article, I will go over the different classes in the System.Collections
and System.Collections.Specialized
namespaces of the .NET Framework 1.1.
The Classes
First, a little introduction to the classes I will be discussing:
In System.Collections
:
ArrayList |
An array that holds objects. |
BitArray |
An array that holds bit (boolean) values. |
HashTable |
A hash table that holds key/value pairs that is organized based on the hash of the key. |
Queue |
A first-in, first-out data structure that holds objects. |
SortedList |
An array of key/value pairs that is sorted by the key values. |
Stack |
A first-in, last-out data structure that holds objects. |
In System.Collections.Specialized
:
HybridDictionary |
A hybrid data structure that uses a ListDictionary if the list is small and a HashTable if the list is larger. |
ListDictionary |
A linked list data structure. It is good for small collections (usually below 10 elements). |
NameValueCollection |
A key/value pair collection for strings. |
StringCollection |
A collection of strings. |
StringDictionary |
A HashTable that is strongly typed for strings. |
The classes ArrayList
and StringCollection
implement the IList
interface.
The classes HashTable
, HybridDictionary
, ListDictionary
, and SortedList
implement the IDictionary
interface.
All these classes implement (or derive) the IEnumerable
interface, which means that traversing the collections can be done with a simple foreach()
statement. Like so:
using System.Collections;
...
ArrayList ar = new ArrayList();
ar.Add("a");
ar.Add("b");
ar.Add("c");
foreach(String s in ar)
{
Console.WriteLine(s);
}
A note on foreach()
: You are not allowed to change the collection as long as the foreach()
loop is running, or the enumerator will fail with an exception.
The Interfaces
IList
The IList
interface supports a number of properties and methods. You can see them all here:
// IList Properties
bool IsFixedSize {get;}
bool IsReadOnly {get;}
object this[int index] {get; set;}
// IList Methods
int Add(object value);
void Clear();
bool Contains(object value);
int IndexOf(object value);
void Insert(int index,object value);
void Remove(object value);
void RemoveAt(int index);
- Use
IsFixedSize
to determine if the list is a fixed size. Iftrue
, it means you cannot add or remove elements, but you can change elements. - Use
IsReadOnly
to determine if the list is read only. Iftrue
, it means you cannot add, remove or change elements. - Use
this
to read or write elements to the list. You do not actually write this, but you use the[]
directly after the objects name. Like so:ArrayList ar = new ArrayList(); ar.Add("a"); Console.WriteLine(ar[0]); // writes a
- Use
Add()
to add elements to the list. - Use
Clear()
to remove all elements from the list. - Use
Contains()
to find out if an element is on the list. - Use
IndexOf()
to get the index of an element on the list. If it does not exist,IndexOf
will return-1
. - Use
Insert()
to insert an element in a specific position on the list. - Use
Remove()
to remove a specific item from the list. It is allowed to try and remove a non-existent element and evennull
. - Use
RemoveAt()
to remove an item from a specific position on the list.
IDictionary
The IDictionary
interface supports a number of properties and methods. You can see them all here:
// IDictionary Properties
bool IsFixedSize {get;}
bool IsReadOnly {get;}
object this[object key] {get; set;}
ICollection Keys {get;}
ICollection Values {get;}
// IDictionary Methods
void Add(object key,object value);
void Clear();
bool Contains(object key);
IDictionaryEnumerator GetEnumerator();
void Remove(object key);
- Use
IsFixedSize
to determine if the list is a fixed size. Iftrue
, it means you cannot add or remove elements, but you can change elements. - Use
IsReadOnly
to determine if the list is read only. Iftrue
, it means you cannot add, remove or change elements. - Use
this
to read or write elements to the list. You do not actually write this, but you use the[]
directly after the objects name. Like so:HashTable ht = new HashTable(); ht.Add("a",null); Console.WriteLine(ht[0]); // writes a
- Use
Add()
to add elements to the list. - Use
Clear()
to remove all elements from the list. - Use
Contains()
to find out if an element is on the list. - Use
Remove()
to remove a specific item from the list. It is allowed to try and remove a non-existent element and evennull
.
IComparable
// IComparable Methods
int CompareTo(object obj);
The CompareTo
method should compare the obj
to the current instance. Return a value less than zero if the current object is less than obj
. Return 0 if the current object is equal to obj
. Return a value larger than zero if the current object is greater than obj
.
IComparer
// IComparer Methods
int Compare(object x,object y);
The Compare
method should compare the two objects x
and y
to each other and return a value less than zero if x
is less than y
, 0 if x
is equal to y
, or a value larger than zero if x
is greater than y
. The preferred implementation is to use the CompareTo
method of one of the parameters.
ArrayList
ArrayList
is the most common choice for an array based list. It can hold any object type, and if the objects in the list implements the IComparable
interface, the class can sort the elements directly by calling the Sort()
method.
The ArrayList
is quite easy to use:
using System.Collections;
...
ArrayList ar = new ArrayList();
ar.Add("The");
ar.Add("quick");
ar.Add("brown");
ar.Add("fox");
ar.Add("jumped");
ar.Add("over");
ar.Add("the");
ar.Add("lazy");
ar.Add("dog");
Accessing the elements is done through an index:
if(((String)ar[1]).Equals("quick"))
ar[1] = (String)"slow";
BitArray
The BitArray
list holds boolean values. They are stored in an efficient manner, since only one bit is required to hold true
or false
.
HashTable
The HashTable
list is a key/value pair type list. The objects used as keys in the list must implement Object.GetHashCode()
and Object.Equals()
, as these are used for determining where the value will be stored in the list.
The value in an element on a HashList
can be null.
Queue
The Queue
list stores object in the order they are added to the list, it is a first-in, first-out data structure.
To add an object to the list, call the Enqueue()
method, and to remove and object from the list, call the Dequeue()
method.
You can also have a look at the object that would be dequeued from the list, without actually removing it, by calling the Peek()
method.
SortedList
The SortedList
list is a key/value pair type list. The list is sorted at all times. The objects added to the list must implement the IComparable
interface, or an object supporting the IComparer
interface must be passed to the constructor when creating the list.
Stack
The Stack
list stores object in the order they are added to the list, it is a first-in, last-out data structure.
To add an object to the list, call the Push()
method, and to remove and object from the list, call the Pop()
method.
You can also have a look at the object that would be popped from the list, without actually removing it, by calling the Peek()
method.
HybridDictionary
The HybridDictionary
list is basically a HashTable
list, but it will use the more efficient ListDictionary
list internally, when the list is small.
Read the description on HashTable
to learn how to use the list.
ListDictionary
The ListDictionary
list is basically a HashTable
list. It is implemented with a linked list and is only efficient when there are 10 or less elements in the list.
Read the description on HashTable
to learn how to use the list.
NameValueCollection
The NameStringCollection
list is a key/value pair type list. The keys are strongly typed to be strings instead of any object.
StringCollection
The StringCollection
list is a strongly typed ArrayList
that stores strings.
StringDictionary
The StringDictionary
list is a HashTable
strongly typed to hold strings.
Read the description on HashTable
to learn how to use the list.
Conclusion
The .NET Framework has a lot of different collection classes. You should now know them all and what makes each and every one special, so that you will know which one to pick for your next project.