Dictionary Collection With A String Comparer

Based on the previous example. What would happen if you had a key value that was uppercase and you executed methods methods with key values in lowercase? You would get an error that the items wasn’t found. Or worse, if adding an item the method would add it. Then you would have multiple elements with the same key value pair. Not a good situation. That’s where the StringComparer class comes in handy when I’ll describe below.


Program.cs Code Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionaryItems
    class Program
        /// Demonstrating how the Dictionary collection works with the StringComparerClass.
        /// This is being used to ignore the string case when searching for an element in the collection.
        /// </summary>

        /// <param name="args"></param>

        static void Main(string[] args)
            // Creating a list of president objects.
            List<President> presidentsList = new List<President>
                new President("GW", "George Washington", 1789),
                new President("JA", "John Adams", 1797),
                new President("JM", "James Monroe", 1817)

            // Creating the presidents object dictionary list.
            Dictionary<string, President> presidentsDictionaryList = createPresidentsDictionary();

            // Adding objects from the generic list into a dictionary list.
            addPresidentsFromListToDictionary(presidentsList, presidentsDictionaryList);

            // Displaying the contents of the list.
            Console.WriteLine("****Displaying The Presidents Dictionary List****");

            // Searching for elements in the dictionary list.
            Console.WriteLine("****Searching The Presidents Dictionary List****");
            searchItems(presidentsDictionaryList, "Gw");


        // Private Methods
        // Method that creates a list to contain objects.
        private static Dictionary<string, President> createPresidentsDictionary()
            // Returning a dictionary with a string comparer object that ignores case.
            return new Dictionary<string, President>(StringComparer.InvariantCultureIgnoreCase);

        // Method that adds a new object to the list.
        private static void addPresidentsFromListToDictionary(List<President> list, Dictionary<string, President> dictionaryList)
            // Taking the objects in the list and adding them to the dictionary.
            foreach (var item in list)
                dictionaryList.Add(item.ID, item);

        // Method that displays the contents of a collection.
        private static void displayItems(Dictionary<string, President> list)
            foreach (var item in list)
                // Displaying just the value of the dictionary list item.

        // Method that searches the contents of a collection.
        private static void searchItems(Dictionary<string, President> list, string keySearch)
            // Using TryGetValue value method so if the key isn't found an exception isn't thrown.
            President president;
            bool presidentFound = list.TryGetValue(keySearch, out president);

            // If the object doesn't exist continue, otherwise display an error.
            if (presidentFound)
                Console.WriteLine("That value isn't in the Dictionary list.");

        // Method that adds an object to the dictionary.
        private static void addItem(Dictionary<string, President> list, President item)
            // If the object exists then display an error, otherwise continue.
            if (itemExists(list, item))
                Console.WriteLine("Sorry That President Is Already In The List");
                list.Add(item.ID, item);

        // Method that checks to see if an object exists in the dictionary.
        private static bool itemExists(Dictionary<string, President> list, President item)
            // Using the TryGetValue method to see if an object exists in the dictionary list.
            President president;
            bool presidentFound = list.TryGetValue(item.ID, out president);
            if (presidentFound)
                return true;
                return false;

All of this code is the same as the Dictionary collection post. The main difference is I’m using an instance of the StringComparer class when I’m creating the dictionary. I’m using the InvariantCultureIgnoreCase property. This property makes so when I’m searching, adding, or removing a dictionary item the case of key value is ignored. This is being demonstrated when I’ calling the searchItems method.


Leave a Reply

Please log in using one of these methods to post your comment:

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