Dictionary Collection With A Custom String Comparer

After working with the dictionary collections, and the string comparers that go with it. I decided to mess around more with the StringComparer class and define my own equality compare class to get an idea of how things work under the hood. This example is taking elements from a list and putting them into three sorted lists. One sorted list without any kind of compare, the second using the build it string compare class, and the third a small custom compare class.

SortedListProgram SortedListSolution

 

MyEqualityComparer.cs Code Contents

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

namespace DictionaryItems
{
    /// <summary>
    /// A custom equality comparer class used with sorted collection types.
    /// </summary>

    public class MyEqualityComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            return String.Compare(x, y, StringComparison.InvariantCultureIgnoreCase);
        }
    }
}

This is a simple comparer class that inherits from the IComparer interface. When an instance of this class is created the Compare() method will be exposed. This method uses an overload of the String.Compare() method with the InvariantCultureIgnoreCase comparison type. What this does is ignore the case of the string parameters being used.

 

Program.cs Code Contents

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

namespace DictionaryItems
{
    class Program
    {
        /// <summary>
        /// Demonstrating how the Sorted List collection works.
        /// This type of list is best used when the list elements don't change that often. Reason for this is element modifications
        /// are slower than other collection types. However this collection type does offer lower overhead and fast lookup of the elements.
        /// </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),
                new President("AJ", "Andrew Jackson", 1829)
            };

            // Creating a SortedList collection without using any type of string comparer.
            SortedList<string, President> presidentsSortedList = new SortedList<string, President>();

            // Creating a SortedList collection using a built in string comparer for the key lookup.
            SortedList<string, President> builtInComparerPresidentsList = new SortedList<string, President>(StringComparer.InvariantCultureIgnoreCase);

            // Creating a SortedList collection using a custom string comparer.
            SortedList<string, President> customComparerPresidentsList = new SortedList<string, President>(new MyEqualityComparer());


            // Adding elements to the SortedList.
            foreach (var item in presidentsList)
            {
                presidentsSortedList.Add(item.ID, item);
                builtInComparerPresidentsList.Add(item.ID, item);
                customComparerPresidentsList.Add(item.ID, item);
            }

            // Searching the sorted list for an element. Catching the exception when it's thrown.
            Console.WriteLine("****Searching For A President Without Any String Comparer****");
            try
            {
                Console.WriteLine("John Adams Is: {0}", presidentsSortedList["ja"]);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine();

            // Searching the sorted list for an element using the built in string comparer.
            Console.WriteLine("****Searching For A President Using A Built In String Comparer");
            Console.WriteLine("John Adams Is: {0}", builtInComparerPresidentsList["ja"]);
            Console.WriteLine();

            // Searching the sorted list for an element using the custom string comparer.
            Console.WriteLine("****Searching For A President Using A Custom String Comparer");
            Console.WriteLine("James Monroe Is: {0}", customComparerPresidentsList["jm"]);
            Console.WriteLine();

            Console.ReadLine();
        }
    }
}

I’m doing that same thing here by creating some President object like I have in some previous examples.

I’m creating three SortedList collections. Two of them are using a version of a string comparer. The default one is here just to show what is available in default form. I’m taking the List, iterating thru it with a foreach loop, and adding the objects to the three lists.

For the search example I’m using a try/catch block to look for the element and to control the way an exception is thrown if the element isn’t found. In the past I’ve done this differently however I wanted to mix things up a little to show a different way of doing it. I’m not using a try/catch block while searching thru the other sorted lists however take note that some kind of error checking or exceptions handling will have to be done. I just didn’t include it for this example for simplicity.

Advertisements

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