#1,131 – Example of Using a Generic Dictionary

Below is an example of using a generic dictionary to count how many times each type of letter appears in a passage of text.  The keys are of type char (the letter found) and the values are of type int (# times found).

            string someText = "One cannot think well, love well, " +
                "sleep well, if one has not dined well.";

            Dictionary<char, int> charCounter = new Dictionary<char, int>();

            foreach (char c in someText)
                if (!charCounter.ContainsKey(c))
                    charCounter.Add(c, 1);
                    // charCounter[c] is of type int,
                    //   c is of type char

            Console.WriteLine("Found {0} unique characters", charCounter.Keys.Count);

            foreach (KeyValuePair<char, int> kvp in charCounter)
                Console.WriteLine("[{0}] - {1} instances", kvp.Key, kvp.Value);