#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

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

3 Responses to #1,132 – Using a SortedDictionary

  1. Pingback: Dew Drop – July 7, 2014 (#1809) | Morning Dew

  2. Emmad Kareem says:

    Thank you for the tips. I was wondering how to start from tip#1 and proceed sequentially?

    • Sean says:

      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.

Leave a Reply to Emmad Kareem Cancel 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: