#1,132 – Using a SortedDictionary

You can use a SortedDictionary<T1,T2> instead of a Dictionary<T1,T2> when you’d like entries sorted in the dictionary by the value of their keys.  Below is an example where we count how many times each letter of the alphabet is found in a particular string.

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

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

            foreach (char c in someText)
            {
                if (char.IsLetter(c))
                {
                    char cLower = char.ToLower(c);
                    if (!charCounter.ContainsKey(cLower))
                        charCounter.Add(cLower, 1);
                    else
                        charCounter[cLower]++;
                }
            }

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

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

1132-001