#1,131 – Example of Using a Generic Dictionary
July 3, 2014 1 Comment
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); else // charCounter[c] is of type int, // c is of type char charCounter[c]++; } 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);
Pingback: Dew Drop – July 3, 2014 (#1808) | Morning Dew