#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);
                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);

1131-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,131 – Example of Using a Generic Dictionary

  1. Pingback: Dew Drop – July 3, 2014 (#1808) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: