In last post about hashtables, I mentioned that there is more efficient type of hashtable called dictionary. I recommend you to read that article before moving to dictionaries. Dictionary is part of System.Generic. Concept of dictionary is the same as Hashtable , A It is a data structure that represents a collection of keys and values pair of data. In dictionaries we need to define the type of variable that will be stored in collection. This makes no need for boxing/unboxing process, what effects the collection performance. Dictionary is part of generic collection what means we can use it with any data types
Lest take a look at example of Dictionary.
class Program { static void Main() { Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("John", 10); dictionary.Add("Bob", 5); } }
Syntax of Dictionary is similar to Generic List, you can read more details about it here.
We can loop through object the same way as we do with hashtables, but in dictionaries we use KeyValuePair structure, it contains key and value of the object
foreach (KeyValuePair<string, int> kvp in dictionary) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); }
we can replace
(KeyValuePair<string, int> kvp in dictionary)
with
(var kvp in dictionary)
what makes code easier to read, and reduce the time of typing
We can search through collection to find value or key we want. Here is another difference between hashtable and dictionary. Dictionary returns error if we try to find a key which does not exist. While Hashtable returns null.
if (dictionary.ContainsKey("Bob") == true) { Console.Writeline(dictionary["Bob"].ToString ()); } else { Console.Writeline("Key does not exist"); }
We can perform much more operations on this collection. But I described the most essential of them. Dictionary is one of the most popular and frequently used collection type. In next post I’ll move to different types of collections like Stack or Queue. Stay Awesome!