Wednesday, February 18, 2015

Dictionary

Intro:

So you like hashsets and want to see some other cool datatypes out there that can manipulate data in cool and efficient ways?  Have no fear, another option is the Dictionary type!  With this data type you get Key/Value pairing storage along quick searching and data manipulation.  Think HashTable but more generically typed so you can pass an Object type versus having to pass a defined type (int/string/etc...).

But enough about defining the Dictionary type, lets write some code!

Coding:

For this adventure I'm going to borrow some data from Bobby's Removing Duplicate Data post (go read it if you haven't already, great stuff).  Adding data is similar to what you'd do for a List (yes i used one in this sample).

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

namespace DictionarySample
{
  class Program
  {
    static void Main(string[] args)
    {
      //step 1: create!
      Dictionary<string, List<string>> myDictionary = new Dictionary<string, List<string>>();
      myDictionary.Add("Daniel",new List<string> { "Slingblade","1001101111","Troll" });
      myDictionary.Add("Bob", new List<string> { "UpandDown","4242424242","Troll" });
      myDictionary.Add("Dan", new List<string> { "TheMan", "ffffffffff", "Troll" });
      myDictionary.Add("Peter", new List<string> { "PumpkinEater", "0110010000", "Lesser-Diety" });
      //step 2: test
      Console.WriteLine("does myDictionary.ContainsKey(chode)? : " + myDictionary.ContainsKey("chode").ToString() + " ");
      Console.WriteLine("does myDictionary.ContainsKey(Peter)? : " + myDictionary.ContainsKey("Peter").ToString() + " ");
      Console.WriteLine("does myDictionary.ContainsKey(peter)? : " + myDictionary.ContainsKey("peter").ToString() + " ");
      //step 3: write out the data
      foreach (var pair in myDictionary)
      {
        Console.Write(pair.Key + " ");
        foreach (string value in pair.Value)
          Console.Write(value + " ");
        Console.WriteLine();
      }
      Console.WriteLine("\nPress Any Key to Exit.");
      Console.ReadKey();
    }
  }
}

And the output:














Step 1 is a fairly easy concept, go create a new Dictionary with whatever datatypes you wish to use.  As they are Key/Value pairs you'll have to have two data types passed in, this is where Bobby's blog data comes into play.  Step 2 I'm doing a little bit of testing to see if Keys exist within my Dictionary, Notice the case sensitivity involved with the Peter/peter test results.  Step 3 is just displaying the data from the Key/Pair values in the Dictionary.

Source:

Microsoft: Dictionary

No comments:

Post a Comment