Click here to Skip to main content
15,879,348 members
Articles / Mobile Apps
Article

Working with collections in the .NET Framework

Rate me:
Please Sign up or sign in to vote.
3.50/5 (16 votes)
21 Jun 20046 min read 74.1K   2   45   4
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:

ArrayListAn array that holds objects.
BitArrayAn array that holds bit (boolean) values.
HashTableA hash table that holds key/value pairs that is organized based on the hash of the key.
QueueA first-in, first-out data structure that holds objects.
SortedListAn array of key/value pairs that is sorted by the key values.
StackA first-in, last-out data structure that holds objects.

In System.Collections.Specialized:

HybridDictionaryA hybrid data structure that uses a ListDictionary if the list is small and a HashTable if the list is larger.
ListDictionaryA linked list data structure. It is good for small collections (usually below 10 elements).
NameValueCollectionA key/value pair collection for strings.
StringCollectionA collection of strings.
StringDictionaryA 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:

C#
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:

C#
// 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. If true, it means you cannot add or remove elements, but you can change elements.
  • Use IsReadOnly to determine if the list is read only. If true, 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 even null.
  • 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:

C#
// 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. If true, it means you cannot add or remove elements, but you can change elements.
  • Use IsReadOnly to determine if the list is read only. If true, 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:
    C#
    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 even null.

IComparable

C#
// 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

C#
// 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:

C#
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:

C#
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Team Leader momondo
Denmark Denmark
Sune has been programming since 1985.

He has worked with both assembler and many different programming languages, such as: Basic, Fortran, Pascal, C, C++, Delphi, and lately C#.

Sune is married and has two small children and is currently working as a developer for a Danish company called Skygate, currenly working on a cheap flight search engine called Momondo.

Personal blog can be found here.

Comments and Discussions

 
GeneralError about Stack Pin
Matteo Casati30-Jul-08 21:21
Matteo Casati30-Jul-08 21:21 
GeneralError about StringCollection Pin
Chad Z. Hower aka Kudzu26-Oct-04 17:52
Chad Z. Hower aka Kudzu26-Oct-04 17:52 
GeneralNeed Help Pin
riyo10-Aug-04 4:03
riyo10-Aug-04 4:03 
GeneralThanks Pin
JCrane222-Jun-04 10:54
JCrane222-Jun-04 10:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.