Zoo tutorials: [ SQL | Linux | XML ]
ProgZoo: [ Java | C# | VB | C++ | Perl ]
Log in

A Gentle Introduction to
C# Programming

Dictionary

 

Data Structures

Dictionary
A hash table (also known as associative array, lookup table, dictionary, hash) is a way of storing values against keys. Often the keys are strings, in this example the values are numbers.
Typical operations required:
add or put or set
insert a new (key,value) pairs
lookup or get
retrieve the value for a given key
iterate
run over every key
hash
keyvalue
andrew2753
sally2742
gordon2754
This structure is so useful that we find it in most programming languages. Often there are many different options that have subtly different characteristics. Usually we want fast retrieval and we may or may not care about: fast insert, efficient use of memory, the order of the keys.

The Dictionary class provides a hashtable in .NET 2

We can use square brackets [] to set and retrieve values. The index can be pretty much anything, strings are often used.

1. [ C# ] Telephone book


Big

When we create the structure we specify the type of the key and the type of the value.

We can lookup the phone number for "Sally" using the get method.

2. [ C# ] Missing items


Big

You don't want to risk trying to retrieve a value that is not in the list. It will cause an exceptions.

Instead we can test using ContainsKey

3. [ C# ] Getting all values back


Big

The property Keys permits this. We can also use Values to get a list of values.

4. [ C# ] Getting keys back in the right order


Big

If you want the keys in order it is best to use a structure that maintains order in the first place. For C# use a SortedDictionary