#1,132 – Using a SortedDictionary
July 7, 2014 3 Comments
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);
Pingback: Dew Drop – July 7, 2014 (#1809) | Morning Dew
Thank you for the tips. I was wondering how to start from tip#1 and proceed sequentially?
Every post has a link to the previous and next posts. So you can go read the first post and then click the link for #2 when you’re ready to move on.