Sorted Dictionary Collection

For an brief explanation look at the summary comments in the Program.cs class.

Program Solution

 

President.cs Code Contents

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

namespace DictionaryItems
{
    /// <summary>
    /// Public class that hold the data of President objects. This includes the name and the year
    /// the president was elected.
    /// </summary>

    public class President
    {
        // Public Read-Only Fields
        //
        public string ID { get; private set; }
        public string Name { get; private set; }
        public int YearElected { get; private set; }

        // Constructors
        //
        public President(string id, string name, int yearElected)
        {
            this.ID = id;
            this.Name = name;
            this.YearElected = yearElected;
        }

        // Public Methods
        //
        public override string ToString()
        {
            return String.Format("{0}, elected: {1}", Name, YearElected);
        }
    }
}

This is a simple class that contains the President objects for this example. There are only three properties. The ID, Name, and YearElected of the president. I’m forcing the use of a constructor to ensure that all the properties are set correctly. I’m also over-riding the ToString method to display the information in the correct format.

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 class is a simple demostration of how you can create a comparer class that inherits from the IComparer interface. The only method is to compare 2 strings. This is used if you don’t wish to use the .NET built in StringComparer class which I’ll be demonstrating also in the Program.cs class.
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 Dictionary collection works.
        /// This type of collection is good for collections that change on a frequent basis.
        /// Trade offs include faster modification of the list, fast lookup of elements, however the overhead is greater than
        /// that of a sorted list or generic list.
        /// </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 SortedDictionaryList collection without using any type of string comparer.
            SortedDictionary<string, President> presidentsSortedList = new SortedDictionary<string, President>();

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

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


            // Adding elements to the SortedDictionaryList.
            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();
        }
    }
}

Again like most of my other examples this class is where everything is being demonstrated. I’m first creating a simple List of the President objects. From there I’m creating three SortedDictionary collections. One not using any kind of string comparer, the second is using the build in .NET string comparer, and the third is using the custom string comparer.

Next I’m performing a simple a demonstration of a possible way to iterate thru the collection and display the elements. The next two examples I’m doing a search by key in the collection using the different string comparer classes. Now keep in mind that if they key isn’t found an exception will be thrown and it will need to be handled correctly.

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