Dictionary Class in C#




Introduction

The Dictionary class gives us the opportunity to map some values to specific keys; in real life scenarios we need this mechanism to represent some values whenever we call the key associated with them according to an event.

The following code snippet maps different keys of countries to show their values represented by avaliable universities in every chosen country.

First we have to import specific namespace which is; using System.Collections.Generic. Secondly, we decalre Countrylist of type Dictionary class represented by string keys and an array of string values, then in the Form1_Load event we populate the Countrylist with appropriate data.

Thirdly, we use countrycomboBox to populate every key in our Countrylist, and according to the choice of every key, the available universities will be shown in lisbox1 via firing countrycomboBox_SelectedIndexChanged event.

Dictio.gif

using System;
using System.Collections.Generic;
using System.Windows.Forms;

 namespace DictionaryClass
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

// Creat Dictionary <Key, Value>  Pairs; Key represented by Type of string while Value represented by  an array of string

        Dictionary<string, string[]> CountryList = new Dictionary<string, string[]>();

        private void Form1_Load(object sender, EventArgs e)
        {

// The following snippet shows every key with its suitable values

            CountryList["Egypt"] = new string[]{"Cairo University", "Ain Shams University","Assuit University"};
            CountryList["Saudia Arabia"]= new string[]{"Alqassam University","Altaef University","King Saud University" };
            CountryList["Malaysia"] = new string[] { "UUM University","USM University","UKM University"};

//Expose countrycomboBox to host keys

            countrycomboBox.Items.Add("--Please Select--");

            foreach (string CountryKey in CountryList.Keys)
            {
                countrycomboBox.Items.Add(CountryKey);
            }
            countrycomboBox.SelectedIndex = 0;
        }
 
        private void countrycomboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedCountry = countrycomboBox.SelectedItem.ToString();

            if (countrycomboBox.SelectedIndex==0)
            {
                listBox1.Items.Clear();
            }
            else
            {

//Expose listBox1 to host values associated with its key.

            listBox1.Items.Clear();
            listBox1.Items.AddRange(CountryList[selectedCountry]);
            }
        }
    }
}

Up Next
    Ebook Download
    View all
    Learn
    View all