Dictionary (TKey, TValue) Collection Example

Here I’ll be explaining some basic usage of the dictionary collection class. Dictionaries are a generic data type that stores values with an associated key. This key is important because it is used for lookup, addition, removing, and indexing of values. The dictionary is intended to be used with any data type as I’ll demonstrate below. What I’ll be doing is creating an object type and storing the type in a dictionary with a key. Then I will perform various tasks on the dictionary like displaying the elements, searching for elements, and removing elements.

DictionaryProgram DictionarySolution

 

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

The President class is being used to create US President objects. The object has an ID property, Name property, and YearElected property. All of the properties are public read-only and private set with the class contructor. I am over-riding the ToString() method for a customized display of how the objects are presented.

 

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 Dictionary collection works.
        /// </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****");
            displayItems(presidentsDictionaryList);
            Console.WriteLine();

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

            // Adding an object to an already created Dictionary.
            President andrewJackson = new President("AJ", "Andrew Jackson", 1829);
            addItem(presidentsDictionaryList, andrewJackson);

            // Displaying the contents of the list with the added object.
            Console.WriteLine("****Adding A President To The Presidents Dictionary List****");
            displayItems(presidentsDictionaryList);
            Console.WriteLine();

            // Removing an object from the dictionary.
            Console.WriteLine("****Removing A President From The Presidents Dictionary List****");
            removeItem(presidentsDictionaryList, andrewJackson);

            // As a test let's try and look for an object that isn't in the Dictionary list.
            // Uncomment lines 57-58 to see the error.
            President test = new President("TestId", "Test Name", 1991);
            removeItem(presidentsDictionaryList, test);

            displayItems(presidentsDictionaryList);
            Console.WriteLine();

            Console.ReadLine();
        }

        // Private Methods
        //
        // Method that creates a list to contain objects.
        private static Dictionary<string, President> createPresidentsDictionary()
        {
            return new Dictionary<string, President>();
        }

        // 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.
                Console.WriteLine(item.Value);
            }
        }

        // 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(president.ToString());
            else
                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");
            else
                list.Add(item.ID, item);
        }

        // Method that removes an object from the dictionary.
        private static void removeItem(Dictionary<string, President> list, President item)
        {
            if (itemExists(list, item))
                list.Remove(item.ID);
            else
                Console.WriteLine("The Object Doesn't Exist.");
        }

        // Method that checks to see if an object exists in the dictionary.
        private static bool itemExists(Dictionary<string, President> list, President item)
        {
            // Using the TyGetValue 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;
            else
                return false;
        }
    }
}

What I’m doing first is creating a List objects. For the objects ID I’ll use the initials. Normally this would be a random number, say a guid, but for this simple example this will work. This id will be used later in the dictionary as the key on the elements objects.

Next I’m calling a method that creates and returns a dictionary of string key and President objects. Then I’m calling a method that executes a foreach loop to add the president objects and their cooresponding keys to the dictionary list. To display the list items I’m just calling a method that executes a foreach loop on the collection making sure to display the listItem.value.

To search for an item in the dictionary the best way is to lookup items using the keyvalue pair. What I’m doing is executing a method that creates an empty President object, executes a bool variable with the collections TryGetValue method outing to the President object if found. Then executing an if/else condition based on the bool variable. If the object is found write it out to the console. If the object isn’t found write out an error message to the console.

Adding an item to and existing list is simple. Just create your object, execute a method to search and make sure there isn’t an existing object with the same key, and add it. I’m doing this by executing a method with the list name, remember reference types, and the president object as parameters. The method executes an if/else condition using the itemExists condition. If that bool returns true there’s an object already in the list and if it returns false the object is added to the list.

To remove an item from the list I’m performing the inverse of adding an item using the same methods that look and make sure the item exists. If so remove the item. If not display an error. To test this I’m creating a test president object, not adding it to the list, and executing the remove method. This will kick back and error showing some safety when performing tasks on a Dictionary list type.

Oh also for the itemExists method. All this method is doing is using the TryGetValue method and using that to return a bool status.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s