c# Dictionaries

I recently discovered how to use the Generic Dictionary class in c# to make a dictionary that holds anything. VB6/VBScript dictionaries use the Scripting.Dictionary class which consist of a string key/value pair. There have been many times that I wanted to store an object in the value part. In c#, I wanted them to keep from looping all the items in a list simply to check existance. Ah, .Contains where art though.

The following lines demonstrate.

//Includes
using System.Collections.Generic;

//Declaration/Instanciation
private Dictionary objContacts = new Dictionary( );

//Existance check
if (objContacts.ContainsKey(nIndex))

//Addition
objContacts.Add(nIndex, objContact);

//Removal
objContacts.Remove(nIndex);

//Iteration
foreach (int nIndex in objContacts.Keys)

//Access element by key
Contact myContact = objContacts[nIndex];

O’Reilly
MSDN IDictionary Interface

Leave a Reply

You must be logged in to post a comment.