The Dictionary C# data structure is extremely useful data structure since it allows the programmer to handle the index keys. What does that mean? Well an ArrayList automatically makes its "keys" integers that go up one by one, 1, 2, etc, so to access a value in an ArrayList one goes like: myArrayList[2];
So what the Dictionary data structure does is let us specify the keys, which can be any type of object. For example:
Dictionary<string, int> myDictionary = new Dictionary<string, int>(); myDictionary.Add("one", 1); myDictionary.Add("twenty", 20);
Retrieving a value is pretty straight forward:
int myInt = myDictionary["one"];
Notice how convenient the Dictionary data structure is, in that there is no need to cast between types. Also there is nothing stopping you from creating a Dictionary like so:
Dictionary<int, Dictionary<string, int>> nestedDictionary = new Dictionary<int, Dictionary<string, int>>();
That is a nested Dictionary C# data structure and it is fair game.
I understand that it can be confusing on how to go about getting all the values out of a Dictionary data structure since we have no way to knowing the pattern in the keys. Luckily we don't have to, here is the code to transverse a C#.Net Dictionary:
//List<[same type as index]> List<string> keyList = new List<string>(myDictionary.Keys); for (int i = 0; i < keyList.Count; i++) { int myInt = myDictionary[keyList[i]];
}
The Hashtable data structure is very very much like the Dictionary data structure. A Hashtable also takes in a key/value pair, but it does so as objects.
Values are then stored in order according to their key's HashCode. The Dictionary on the other hand keeps the values in the order they were added.
(For those Java programmers, a Dictionary is more or less a TreeMap with a Hashtable being a HashMap).
Hashtable myTable = new Hashtable();
The HashSet data structure was introduced in C# Net 3.5. This particular C# data structure very strongly resembles the List<> data strucuture.
So what is the difference? A HashSet has the very important characteristic that it does not allow duplicate values. For example:
HashSet<int> mySet = new HashSet<int>(); mySet.Add(3); mySet.Add(5); mySet.Add(3); mySet.Add(10); List<int> myListFromSet = mySet.ToList<int>(); int myInt = myListFromSet[2];
If mySet were a regular List data structure, the index 2 should return the value 3 (count it out). But if you run the example you will see that myInt actually returns the value 10. This is because the HashSet C# data structure ignored the duplicate addition of the value 3...
Continue C# Data Structures - Page 3
Stack, Queue >>>