Tuesday, November 25, 2014

The Dictionary Collections


namespace The_Dictionary_Collection
{

    public class Student
    {
        string _firstname;
        string _lastname;
        DateTime _dateOfBirth;
        string _stuID;

        public Student(string firstname, string lastname, string stuID, DateTime dateOfBirth)
        {
            this._dateOfBirth = dateOfBirth;
            this._firstname = firstname;
            this._lastname = lastname;
            this._stuID = stuID;
        }

        public string StuID
        { get { return this._stuID; } }
        public string Firstname
        { get { return this._firstname; } }
        public string Lastname
        { get { return this._lastname; } }
        public DateTime DateOfBirth
        { get { return this._dateOfBirth; } }
    }
}
//===================================================================
namespace The_Dictionary_Collection
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// Important LEVEL = ***** (FIVE STARS): Most likely to include in interview
        /// what is hashtable?
        /// how do you solve collision issue
        /// 
        /// Dictionary collection
        /// *********************
        /// Prior to System.Collections.Generic, we used the System.Collections
        /// Instead of Dictionary, we used Hashtable
        /// A Dictionary works the same as Hashtable, except it is generic
        /// A hashtable borrows its name from has functions that generate a hash code
        /// ref: http://en.wikipedia.org/wiki/Hash_table
        /// 
        /// A Dictionary (or Hashtable) is a collection of key/value pairs that are 
        /// organized based on the hash code of the key. (the hash code of the key is the
        /// index where a value is store)
        /// 
        /// .net dictionary syntax:
        /// Dictionary<TKey, TValue>, TKey is the key data type, and TValue is the value data type
        ///                         (usually TKey is a string)
        /// 
        /// </summary>
        /// ============================================================
        /// Create a Dictionary collection

        Dictionary<string, Student> studentDictionary = new Dictionary<string, Student>();

        //Every time you save a student object in the dictionary,
        //you are actually saving a combination of the key (stuID)
        //and the value (student object)
       
        //this combination is called KeyValuePair
        //.Net defines a KeyValuePair(TKey, TValue)
        //ref: http://msdn.microsoft.com/en-us/library/5tbh8a42(v=vs.110).aspx
        //so in our studentDictionary the KeyValuePair is
        //KeyValuePair<string, Student>

        //Every storage space in the Dictionary is of type KeyValuePair

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Preload the studentDictionary with few students
            PopulateStudentDictionary();

            //populate combobox cboKeys with all the keys in the studentDictionary
            //A dictionary defines a property Keys that gets a collection containing
            //all the keys in the dictionary

            //Dictionary<string, Student>.KeyCollection keys = studentDictionary.Keys;
            //ref:http://msdn.microsoft.com/en-us/library/yt2fy5zk(v=vs.110).aspx
            string[] keys = studentDictionary.Keys.ToArray();
            cboKeys.Items.AddRange(keys);
            cboKeys.Text = "Select a key";

        }
        private void PopulateStudentDictionary()
        {
            Student student = new Student("Zau", "Bawk", "8888", new DateTime(1995, 3, 21));
            //use the Add method to add a Value to a dictionary
            studentDictionary.Add(student.StuID, student);
            //the Add method needs both the key and the object you want to save
            //the key is hashed (converted thru some algorithm, or some hash function)
            //to an index, the student object is saved at that index.
            // you have no knowledge of the index value and it is not sequential.

            student = new Student("John", "Doe", "8825", new DateTime(1990, 8, 06));
            studentDictionary.Add(student.StuID, student);

            student = new Student("Seng", "Mary", "8155", new DateTime(1994, 6, 16));
            studentDictionary.Add(student.StuID, student);

            student = new Student("Grace", "Lama", "9852", new DateTime(2013, 11, 25));
            studentDictionary.Add(student.StuID, student);


        }

        private void btnDisplayDictionary_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            foreach (KeyValuePair<string, Student> kvp in studentDictionary)
            {
                string key = kvp.Key; // key
                Student student = kvp.Value;//value

                listBox1.Items.Add(String.Format("{0} {1} {2} {3}",
                    student.StuID.PadRight(15),
                    student.Firstname.PadRight(14),
                    student.Lastname.PadRight(10),
                    student.DateOfBirth.ToShortDateString().PadLeft(10)));
            }
        }

        private void btnGetStudent_Click(object sender, EventArgs e)
        {
            Display(studentDictionary);
        }

        private void btnRemoveStudent_Click(object sender, EventArgs e)
        {
            //get key from user
            string key = cboKeys.Text;
            if (studentDictionary.Remove(key))
            {
                MessageBox.Show(String.Format("Student with key: {0} has been remove", key));
                Display(studentDictionary);
            }
            else
            {
                MessageBox.Show("Invalid key");
            }
        }
        private void Display(Dictionary<string, Student> dictionary)
        {
            listBox1.Items.Clear();
            foreach (KeyValuePair<string, Student> kvp in studentDictionary)
            {
                string key = kvp.Key; // key
                Student student = kvp.Value;//value

                listBox1.Items.Add(String.Format("{0} {1} {2} {3}",
                    student.StuID.PadRight(15),
                    student.Firstname.PadRight(14),
                    student.Lastname.PadRight(10),
                    student.DateOfBirth.ToShortDateString().PadLeft(10)));
            }
        }
    }
}
//Lab assignment: New Project
//Create a dictionary to hold books
//Define a Book class: _title, _author, _ISBN, _price
//in Form_Load pre-populate dictionary with about ten books. 
//Add functionality to:
    //Add New book to the dictionary
    //Display all the books in the dictionary
    //Search for a book in the dictionary
    //Remove a book from the dictionary.

No comments:

Post a Comment