Search This Blog

Friday, May 23, 2014

Dictionary C# Example

C# > Generics > Dictionary 

Dictionary is a collection of keys and values.
Retrieving a value by using its key is very fast because the Dictionary class is implemented as a hash table.

Example


    Dictionary<string, string> accesCode = new Dictionary<string, string>();

            accesCode.Add("AAA", "PERSON 1");
            accesCode.Add("BBB", "PERSON 2");
            accesCode.Add("CCC", "PERSON 3");

            string code = "";
            accesCode.TryGetValue("xxx", out code); // code = null
            accesCode.TryGetValue("CCC", out code); // code = PERSON 3

            if (!accesCode.ContainsKey("DDD"))
                accesCode.Add("DDD", "PERSON 4");


            foreach (KeyValuePair<string, string> kvp in accesCode)
            {
                MessageBox.Show(kvp.Key + kvp.Value);
            }