Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with Dictionary using Csharp and ASP.NET

In this article we will talk about dictionary. Dictionary store the data in such a manner that you can find a data in efficient way.

Introduction:

Searching data is very useful in applications. Dictionary store the data in such a manner that you can find a data in efficient way. Dictionary collection class stores data in key and value pair.

This article will cover the following topics:

  • Dictionary - Add Item
  • Dictionary - Delete Item
  • Dictionary - Search by Key
  • Dictionary - Search by Value
  • Dictionary - Display Data
  • Dictionary - Other Functionality

Initial UI and Dictionary Data

Figure 1: Initial UI and Dictionary Data

ASP.NET Script:

The below ASP.NET script is used to demonstrate the Dictionary functionality. The script has textboxes, labels and few buttons. As you can see that color data is used to explain the functionality.

Listing 1: ASP.NET Script for Dictionary Demonstrate

<head runat="server">
    <title>MrBool.com - Dictionary Tutorial</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Dictionary Item:
        <asp:TextBox ID="txtDictionaryKey" runat="server"></asp:TextBox> 
        <asp:TextBox ID="txtDictionaryValue" runat="server"></asp:TextBox>
        <br />
        <br />
        Message:
        <asp:Label ID="lblDisplay" runat="server" Text=""></asp:Label>
        <br />
        <br />
        SortedList State:
        <asp:Label ID="lblDictionaryState" runat="server" Text=""></asp:Label>
        <br />
        <br />
         <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
         <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
         <asp:Button ID="btnSearchbyKey" runat="server" Text="Search by Key" OnClick="btnSearchbyKey_Click" />
         <asp:Button ID="btnSearchbyValue" runat="server" Text="Search by Value" OnClick="btnSearchbyValue_Click" />
    </div>
    </form>
</body> 

C# Code:

All dictionary logic is added in C#, you have to include the following namespaces to properly use the dictionary class.

Listing 2: Including namespaces

using System;
using System.Collections.Generic;

Now create the dictionary object and initialize it . The below code snippet will create a ColorDictionary object and then initialize it.

Listing 3: Creating ColorDictionary

static Dictionary<string, int> ColorDictionary; 
ColorDictionary = new Dictionary<string, int>();

The above dictionary is a key value pair, key is type of string and value is type of int. you can define any type of key value pairs as per the requirement.

Dictionary - Add Item:

To add a key value pair in dictionary, First check into dictionary that the given key should not exit in it. Note that key should be unique and can not insert duplicate key. After checking insert the pair by using Add() method.

Add Item - A Key, Value Pair Added

Figure 2: Add Item - A Key, Value Pair Added (“Pink”, 20)

Listing 4: Dictionary - Add Item Source Code

protected void btnAdd_Click(object sender, EventArgs e)
    {
        int intValue;
        Int32.TryParse(txtDictionaryValue.Text, out intValue);

        if (intValue >= 0 && txtDictionaryKey.Text.Trim() != "")
        {
            if (!ColorDictionary.ContainsKey(txtDictionaryKey.Text.Trim()))
            {
                ColorDictionary.Add(txtDictionaryKey.Text.Trim(), intValue);

                lblDisplay.Text = "Dictionary Item Added";
            }
            else
            {
                lblDisplay.Text = "Dictionary - Key Already Exist";
            }
        }
        else
        {
            lblDisplay.Text = "Dictionary - Please Enter an Item to Add";
        }
        DisplayData();
    }
 

Dictionary - Delete Item:

C# dictionary provide remove() method to remove a pair by passing the key. The below example deleting the Green,2 pair by passing the key.

Delete Item - (Green,2) is removed from Dictionary

Figure 3: Delete Item - (Green,2) is removed from Dictionary

Listing 5: Dictionary - Delete Item Code

protected void btnDelete_Click(object sender, EventArgs e)
    {

        if (txtDictionaryKey.Text.Trim() != "")
        {
            if (ColorDictionary.ContainsKey(txtDictionaryKey.Text.Trim()))
            {
                ColorDictionary.Remove(txtDictionaryKey.Text.Trim());

                lblDisplay.Text = "Dictionary Item Deleted";
            }
            else
            {
                lblDisplay.Text = "Dictionary - Item Not Found.";
            }
        }
        else
        {
            lblDisplay.Text = "Dictionary - Please Enter an Item to Delete";
        }
        DisplayData();
    } 

Dictionary - Search by Key:

You can search the dictionary items by key and value. C# provide ContainsKey() method to search the key in dictionary.

Search by Key - The ‘Blue’ found in dictionary key

Figure 4: Search by Key - The ‘Blue’ found in dictionary key

Listing 6: Dictionary - Search by Key - Code

protected void btnSearchbyKey_Click(object sender, EventArgs e)
    {
        if (txtDictionaryKey.Text.Trim() != "")
        {
            if (ColorDictionary.ContainsKey(txtDictionaryKey.Text.Trim()))
            {
                lblDisplay.Text = "Dictionary Item Found";
            }
            else
            {
                lblDisplay.Text = "Dictionary Item Not Found.";
            }
        }
        else
        {
            lblDisplay.Text = "Dictionary - Please Enter an Item to Search";
        }
        DisplayData();
    }
 

Dictionary - Search by Value:

Use ContainsValue to search a value in the dictionary. The other option is to loop through all the items using foreach.

Search by Value - The value 10 found in Dictionary

Figure 5: Search by Value - The value ‘10’ found in Dictionary

Listing 7: Dictionary - Search by Value - Code

protected void btnSearchbyValue_Click(object sender, EventArgs e)
    {
        int intValue;
        Int32.TryParse(txtDictionaryValue.Text, out intValue);

        if (intValue > 0)
        {
            if (ColorDictionary.ContainsValue(intValue))
            {
                lblDisplay.Text = "Dictionary Item Found";
            }
            else
            {
                lblDisplay.Text = "Dictionary Item Not Found.";
            }
        }
        else
        {
            lblDisplay.Text = "Dictionary - Please Enter an Item to Search";
        }
        DisplayData();
    } 

Dictionary - Display Data:

Use foreach loop to display data in Dictionary. As you know that C# dictionary is collection class, so you can use the foreach loop with dictionary to display all data.

Listing 8: Dictionary - Loop through items and display data

private void DisplayData()
    {
        lblDictionaryState.Text = "";

        foreach (KeyValuePair<string, int> pair in ColorDictionary)
        {
            lblDictionaryState.Text += "," + pair.Key + ":" + pair.Value;
        }
        lblDictionaryState.Text = lblDictionaryState.Text.TrimStart(',');
    } 

Dictionary - Other Functionality:

Apart from above functionalities C# dictionary provide some more common functions.

  • TryGetValue - Get the value if key exist and will not throw exception incase the key does not exist.
  • Count - Return the number of items
  • ColorDictionary["Red"] - provide indexer capability - access the values by key

Listing 9: Dictionary - Other operation

 
private void OtherFunctionality()
    {
        int intValue = 0;

        lblDisplay.Text = " Get the index of Value: " + ColorDictionary.TryGetValue("Red", out intValue);

        //Clear all the items of Dictionary
        ColorDictionary.Clear();

        lblDisplay.Text = " Count of All the Items of Dictionary: " + ColorDictionary.Count;

        lblDisplay.Text = " Disctionary Value by key: " + ColorDictionary["Red"];

    } 

Conclusion:

The generic dictionary is great feature available with .NET, use it whenever required. I hope this article is useful for you, Please comment and suggest in case you have any queries or doubts.



I am having total 7+ years of experience in developing applications using C#, VB.NET, ASP.NET, Silverlight, WCF, SQL Server and Oracle. I am holding a M.Tech degree in Intelligent systems. For more information, visit my Linkedin p...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login